This tutorial will introduce built-in functions for string manipulation and conversion. Using these string operation functions, you can perform tasks such as converting numbers to strings and formatting strings.
Common Operation Methods
| Method | Parameter | Description |
|---|---|---|
| str() | x | Converts x to a string type. |
| ascii() | x | Converts x to ASCII code. |
| bin() | x | Converts the number x to a binary string. |
| oct() | x | Converts the number x to an octal string. |
| hex() | x | Converts the number x to a hexadecimal string. |
| chr() | x | Converts x to the Unicode character it represents. |
| ord() | x | Converts the Unicode character represented by x into the corresponding encoding number. |
str(x)
This function converts parameter x to a string type. Whether the input is a number, list, tuple, or boolean value, it will be converted to plain text. For example, after converting the list [1,2,3] to a string, the first character is [. If the input is the boolean value True, converting it to a string results in True, not 1.
a = str(123) b = str([1,2,3]) c = str(True) d = str(False) print(a) # 123 print(b) # [1,2,3] print(b[0]) # [ ( Since it is plain text, the first character is [ ) print(c) # True print(d) # False print(c+d) # TrueFalse ( Since it is plain text, this becomes string concatenation )
ascii(x)
This function converts parameter x to ASCII code.
a = ascii('你好') print(a) # '\\u4f60\\u597d'
bin(x)
bin(x) converts the numeric parameter x into a binary string.
a = bin(1234) print(a) # 0b10011010010
oct(x)
oct(x) converts the numeric parameter x into an octal string.
a = oct(1234) print(a) # 0o2322
hex(x)
hex(x) converts the numeric parameter x into a hexadecimal string.
a = hex(1234) print(a) # 0x4d2
chr(x)
chr(x) converts parameter x to the Unicode character it represents.
a = chr(101) b = chr(202) c = chr(9999) print(a) # e print(b) # Ê print(c) # ✏
ord(x)
ord(x) is the inverse of chr(x): it converts the Unicode character represented by parameter x into the corresponding encoding number.
a = ord('e') b = ord('Ê') c = ord('✏') print(a) # 101 print(b) # 202 print(c) # 9999
This is a separate discussion topic split from the original thread at https://juejin.cn/post/7368665381731450895