-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_operators.py
50 lines (38 loc) · 1.57 KB
/
string_operators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
nombre = 'Jaume'
altura = 1.73
print('Nombre: %s, altura: %.2f' % (nombre, altura))
data = ('Jaume', 'Ordinas', 100.77)
format_string = 'Hello %s %s. Your current balance is $%s.'
print(format_string % data)
## print(format_string, data[0], data[1] + '. Your current height is %.2fm' % data[2])
text = "abcdefghi"
# text[start:stop:step]
# text[x:y] donde "x" entra dentro del rango y "y" és el límite del rango, este no se incluye
print(text[2:7:1])
# EXERCICE
s = "Strings are awesome!"
# Length should be 20
print("Length of s = %d" % len(s))
# First occurrence of "a" should be at index 8
print("The first occurrence of the letter a = %d" % s.index("a"))
# Number of a's should be 2
print("a occurs %d times" % s.count("a"))
# Slicing the string into bits
print("The first five characters are '%s'" % s[:5]) # Start to 5
print("The next five characters are '%s'" % s[5:10]) # 5 to 10
print("The thirteenth character is '%s'" % s[12]) # Just number 12
print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing)
print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end
# Convert everything to uppercase
print("String in uppercase: %s" % s.upper())
# Convert everything to lowercase
print("String in lowercase: %s" % s.lower())
# Check how a string starts
if s.startswith("Str"):
print("String starts with 'Str'. Good!")
# Check how a string ends
if s.endswith("ome!"):
print("String ends with 'ome!'. Good!")
# Split the string into three separate strings,
# each containing only a word
print("Split the words of the string: %s" % s.split(" "))