Python learning notes-string
Today, I learned about Python's basic processing of strings, and I feel it will be helpful for automated scripts in my work to send CLI commands.
First, the most important thing is %, which is the nominal "conversion specifier" for string formatting.
Place a string (formatted string) on the left and the value to be formatted (value to be formatted) on the right)
12345 |
left = "Hello,%s good " # % S indicates the type to be formatted right = "she's" Print left % right # % is used to separate the formatted string from the value to be formatted. Hello,she's good |
NOTE: If s is not added after %, the program reports an error
TypeError: float argument required, not str
If right is not a string, str is used to convert it into a string.
1234 |
print "Price of eggs: $%d" % 42 print "Price of eggs in HEX: $%x" % 42 Price of eggs: $ 42 Price of eggs in HEX: $2a |
In addition, the string module also provides many useful methods, such as the subsutitute method in the Template to replace the string.
1234567 |
from string import Templates s=Template( "$x loves some one" ) print (s.substitute(x= 'she' )) print s she loves some one 0x105bc1350 > |
The first print is the replaced string, and the second print is the template.
The following methods are commonly used for string operations:
Find, equivalent to in
12345678 |
s= "the best movie" print s.find( 'movie' ) print 'movie' in s print s.find( 'movie' , 10 ) # Provide the starting point from index 10 Start searching print s.find( 'movie' , 1 , 5 ) # Provide the start and end points from the index 1 Locate index 59 True - 1 - 1 |
Join & split, join and split string
12345678910 |
from macpath import join s=[ ' ' , 'root' , 'home' ] print '//' .join(s) s1= 'C:' + '\\' .join(s) print s1 print s1.split( '\\' ) //root//home C: \root\home [ 'C: ' , 'root' , 'home' ] |
Note that \ is used. If you only write \, the Program understands the special ASCII symbol \ r because the \ character is not the original character, press enter.
12345 |
s1 = 'C:\root\home' print s1 C: oot\home |
So we use \ and escape characters \ to escape, that is, to tell the program \ is part of the string.
Another way is to use the original string, which is not special to the backslash:
123 |
s=[ ' ' ,r 'root' , 'home' ] print 'C:' + '/' .join(s) C: /root/home |
Strip, remove characters on both sides of the string (the default is space)
Translate, which is the same as replace, but can be replaced at the same time, which is more efficient.
For example, replace c in the string with k and s with z.
12345678910 |
from string import maketrans table = maketrans( 'cs' , 'kz' ) # Create a replacement rule table print len(table) print 'this is a magnificent day!' .translate(table, '!' ) # The second parameter is used to specify the characters to be deleted. 256 thiz iz a magnifikent day |
Divided by the upper and lower layers, there are lower, replace, capitalize and other uncommon methods.
Welcome to my personal website