Learning Python's basic handling of strings today is a great way to feel useful for sending CLI commands to an automated script at work.
The first and foremost is the%, nominally "conversion specifier (conversion specifier)", used for string formatting.
Place a string (formatted string) on the left and the right side to the value you want to format (the value to be formatted)
left = "hello,%s good" #%s indicates the type expected to be formatted right = "She's" print left% right #% used to separate the formatted string and the value to be formatted Hello,she ' s go Od
Note that if you do not add s after%, the program error says
Typeerror:float argument required, not str
If right is not a string, it is converted to a string using str.
Print "Price of Eggs: $%d"%42 print "price of eggs in hex: $%x"%42 price of eggs: $42price of eggs in hex: $2a
In addition to this, string module strings provide a number of useful methods, such as the Subsutitute method in the template to replace strings.
From string import templatess=template ("$x loves some One") print (S.substitute (x= ' she ')) print s She loves some One<stri Ng. Template Object at 0x105bc1350>
The first time you print the replaced string, the second time you print the template.
There are several common methods of string manipulation:
S= "The best movie" Print S.find (' movie ') print ' movie ' in s print s.find (' movie ', ten) #提供起始点, starting from index 10 looking for print s.find (' movie ', 1,5) #提供起始点和结束点, find index 59true-1-1 from index 1
From Macpath import joins=[', ' root ', ' home ']print '//'. Join (s) s1= ' C: ' + ' \ \ '. Join (s) Print S1 print s1.split (' \ \ ')//roo T//homec: \root\home[' C: ', ' root ', ' home '
The note here is \ \, if only writing \, because the non-original string will be recognized as an escape symbol, so the program understands \ r This special ASCII symbol, both enter.
S1 = ' C:\root\home ' Print s1c:oot\home
So we use \ \, with escape notation \ to escape \, that is, to tell the program \ is part of the string.
Another way to do this is to use the original string, which does not have a special treatment for backslashes:
S=[', R ' Root ', ' home ']print ' C: ' + '/'. Join (s) C:/root/home
-
Strip, removing characters on both sides of the string (the default is a space)
-
Translate, same as replace, but can be replaced at the same time, more efficient.
For example, to replace C in a string with K, replace S with Z.
From string Import maketranstable = Maketrans (' cs ', ' KZ ') #建立一张替换规则表print len (table) print ' This is a magnificent day! '. Translate (table, '! ') #第二个参数用来指定要删除的字符256thiz iz a magnifikent day
In addition to the above, there are lower, replace, capitalize and other less commonly used methods.
Python Learning Notes-strings