Python-a02-String

This article shows the examples of String in python

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
51
52
53
# 1
message1 = 'Hello World'
print(message1)

# 2
message2 = "hello 'Jimmy'"
print(message2)

# 3
message3 = 'Hello World'
print(len(message3))

# 4
message4 = 'Hello World'
print(message4[1])
print(message4[-1])
print(message4[0:5]) # first include, second not
print(message4[:5]) # end to the 5
print(message4[6:]) # start from the 6
print(message4[11]) # error

# 5
message5 = 'Hello World'
print(message5.lower())
print(message5.upper())
print(message5.count('l')) # count l's number in the message
print(message5.find('World')) # return 6
print(message5.find('Unknown')) # return -1

# 6
message6 = 'Hello World'
# or by the same message6 = message6.replace('World', 'You')
new_message6 = message6.replace('World', 'You')
print(new_message6)

# 7
greeting='Hello'
name='Bob'
message7 = greeting + ', ' + name
print(message7)

message8 = '{}, {}. Welcome!'.format(greeting, name)
print(message8)

message9 = f'{greeting}, {name}. Welcome!' # python >3.10
print(message9)

message10 = f'{greeting}, {name.upper()}. Welcome!' # python >3.10
print(message10)

# 8
print(help(str))
print(help(str.lower))