Some basics about string objects in Python
- 2020-05-07 19:56:24
- OfStack
The strings of Python are classified as immutable sequences, meaning that the characters contained in these strings are sequenced from left to right and cannot be modified locally.
basic operation
Strings can be combined with the + operator and repeated with the * operator.
>>>len("abc")
3
>>>'abc'+'def'
'abcdef'
>>>'NI!'*4
'NI!NI!NI!NI!'
A backslash "\" inside the string allows the string to be placed on multiple lines.
>>>str = "aaa\
....bbb\
....ccc\
....ddd"
>>>str
aaabbbcccddd
index and shard
In Python, the characters in a string are extracted by index.
Shard X[I:J], which means "take the contents in X from offset I to but excluding offset J". The result is to return a new object.
In 1 shard, the left boundary defaults to 0, and the right boundary defaults to the length of the shard sequence.
S = 'Spam'
>>>S[1:]
'pam'
>>>S
'Spam'
>>>S[:3]
'Spa'
>>>S[:-1]
'Spa'
>>>S[:]
'Spam'
S[:] To achieve the 1 A full copy of the top-level sequence object -1 Objects that have the same value but are different memory areas.
X[I:J:K] "Index x The element in the object, from offset to I Until the offset is J-1 every K Element index 1 ", the first time 3 A limit K By default, 1 Is a step forward.
You can also use negative Numbers as steps, S[::-1] Is actually used to transmit the sequence.
>>>S = 'hello'
>>>S[::-1]
'olleh'
string conversion tool
The int function converts a string to a number, and the str function converts a number to a string representation. The repr function is also able to convert an object to its string form, and the returned objects are then used as strings for the code to recreate the object.
immutable
Strings are immutable sequences, meaning that you cannot change one string in place, for example, to assign an index. To change a string, use tools like merge, shard to create and assign a new string, and if necessary, assign the result to the original variable name of the string.
>>>S = 'spam'
>>>S[0] = "x"
# No modification allowed S The value of the
>>>S = S + "SPAM"
>>>S
'spamSPAM'
>>>S = 'splot'
>>>S = S.replace('pl', 'plmal')
>>>S
'splmalot'