Here's how to create a str string:
s="123456"S2=str ("123456") s3=Str () ; Print (s) Print (S2) Print (S3) # result 123456123456# a space to come, this line
STR is commonly used in the following ways:
#remove the left and right spaces of the strings="Ljiudoang"Print(S.strip ())#start with what?Print(S.startswith ("Lji"))#replaces a subsequence in a string with a specified valuePrint(S.replace ("LJ","BB"))#Turn the string into uppercasePrint(S.upper ())#to determine if a string is a letterPrint(S.isalpha ())
Index and slice of STR:
the index of STR can only represent one character, while the slice of Str can represent more than one character s=""# index print (S[0]) # slices Print (S[0:3])
When encoding with Utf-8, a Chinese is equal to three characters. When encoding with GBK, a Chinese is equal to two characters.
At 3.5, when you calculate with Len and for, it is calculated by the characters. At 2.7, the calculation is done by byte.
# The S string has four Chinese, which is four characters. When using for loop, a character a loop s=" old Chen handsome " for in s: Print (temp)print(len (s))
How to convert a character to a byte. The byte default is a 16 binary number, which is represented by the 16 binary. One byte equals 8 binary digits.
#The S string has four Chinese, which is four characters. When looping with for, a character is a loop#converts a character to three bytes by bytess="Old Chen Handsome" forTempinchS:Print(temp)Print(Bytes (temp,encoding='Utf-8'))#result OutputOld b'\xe8\x80\x81'Chen B'\xe9\x99\x88'Handsome b'\xe5\xb8\x85'Brother B'\xe5\x93\xa5'
When you loop a byte list with a For loop, the byte is automatically converted to a 10-binary representation of the
# make a byte into a 10- s=" old Chen handsome " for in s: Print (temp) byte_list=bytes (temp,encoding='utf-8') for in byte_list: print(i)
#结果展现
Old
232
128
129
With
233
153
136
Handsome
229
184
133
Brother
229
147
165
Converts a decimal number to a binary number by using the Bin method to convert the decimal into binary
s=" old Chen handsome " for in s: print(temp) Byte_ List=bytes (temp,encoding='utf-8') for in byte_list: print(i) r=Bin (i) Print (r)
Convert bytes to Characters
#two encoding modes to byte charactersB1=bytes ("I love you .", encoding='Utf-8') B2=bytes ("you want to be beautiful.", encoding='GBK')Print(B1)Print(B2)#Convert bytes to charactersB3=str (b1,encoding="Utf-8") B4=str (b2,encoding="GBK")Print(b3)Print(B4)
#结果展现:
B ' \xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0 '
B ' \xc4\xe3\xcf\xeb\xb5\xc3\xc3\xc0 '
I love you
You want to be beautiful.
Python Variable str knowledge