Python strings are classified as immutable sequences, meaning that these strings contain characters that are left to right in order, and that they cannot be modified locally.
Basic operations
Strings can be merged by the + operator, which can be duplicated using 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
Indexing and fragmentation
In Python, characters in strings are extracted by index.
Fragment X[i:j], which means "take out the content from an offset of I in x until it does not include an offset of J". The result is to return a new object.
In a fragment, the left boundary defaults to 0, and the right boundary defaults to the length of the fragment sequence.
S = ' Spam '
>>>s[1:]
' pam '
>>>s
' Spam '
>>>s[:3]
' Spa '
> >>s[:-1]
' Spa '
>>>s[:]
' Spam '
s[:] Implements a complete copy of the top-level sequence object-a object that has the same value, but is a different memory slice area.
X[i:j:k] represents "an element in an index X object, from an offset of I until the offset is J-1, every k element is indexed once", and the third limit K, which defaults to 1, indicates stepping.
You can also use negative numbers as stepping, and s[::-1] is actually going to send the sequence forward.
>>>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 can also convert an object to its string form, and the returned objects will be used as strings of code to recreate the object.
Non-denatured
A string is a mutable sequence, that is, a string cannot be modified in situ, for example, to assign a value to an index. To change a string, you need to use a tool such as merge, fragment 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"
#不允许修改S的值
>>>s = S + "spam"
>>>s< c25/> ' spamspam '
>>>s = ' Splot '
>>>s = s.replace (' pl ', ' plmal ')
>>>s
' Splmalot '