Detailed explanation of strings in Python

1. String

In Python, strings belong toImmutable, ordered sequence,useSingle quotes, double quotes, triple single quotesOr triple double quotes as delimiters, and different delimiters can be nested within each other.

‘abc’、‘123’、‘中国’
“Python”
‘’‘Tom said,“Let’s go”’‘’

In addition to supporting common sequence methods (including bidirectional indexing, size comparison, length calculation, element access, slicing, membership testing, etc.), the string type also supports some unique operation methods, such as string formatting, search, replacement, typesetting, etc. etc.
String belongs toImmutable, ordered sequence, you cannot directly add, modify, or delete elements to the string object. Slicing operations can only access the elements and cannot use slicing to modify the characters in the string.

1. Escape characters and original strings

Insert image description here

>>> print('Hello\nWorld')          #包含转义字符的字符串
Hello
World
>>> print('\101')                  #三位八进制数对应的字符
A
>>> print('\x41')                  #两位十六进制数对应的字符
A
>>> print('我是\u8463\u4ed8\u56fd')#四位十六进制数表示Unicode字符
我是董付国

In order to avoid escaping escape characters in a string, you can use a raw string. Add the letter r or R in front of the string to represent the raw string. All characters in it represent the original meaning without any escape. righteous.

>>> path = 'C:\Windows\notepad.exe'
>>> print(path)                       #字符\n被转义为换行符
C:\Windows
otepad.exe
>>> path = r'C:\Windows\notepad.exe'  #原始字符串,任何字符都不转义
>>> print(path)
C:\Windows\notepad.exe

2. Use the % operator for formatting

Insert image description here

print('%+010.2f'%-12.4567)
-000012.46

Insert image description here

3. String slicing

Basic expression of slicing operation: object[start: end:step]

a='hello world'
print(a[:-1])

Insert image description here

Guess you like

Origin blog.csdn.net/qq_52108058/article/details/133912609