String formatting
>>> '%s plus%s equals%s '% (1,1,2) ' 1 plus 1 equals 2 '
Width and precision of fields
* Field width is the minimum number of characters retained by the converted value, the precision (for numbers) is the number of decimal digits that are included, or (for characters) the maximum number of characters that the converted value can contain
>>> from math import pi>>> '%10f ' percent pi ' 3.141593 ' >>> from math import pi>>> '%10f ' % pi #字段宽10 ' 3.141593 ' >>> '%10.2f '% pi #字段宽10, accuracy 2 ' 3.14 ' >>> '%.2f '% pi #精度2 ' 3.14 ' >& Gt;> '%.5s '% ' My name is Ningsi ' my Na ' >>> '%.*s ' percent (5, ' My name is Ningsi ') ' My Na '
Symbols, alignments, and 0 fills
>>> '%010.2f '% pi #用0填充 ' 0000003.14 ' >>> '%-10.2f '% pi #左对齐 ' 3.14 ' >>> print ('% 5d '% + ' \ n ' + ('%5d '% -10) -10>>> print ('%+5d '%) + ' \ n ' + ('%+5d '% -10) +10 -10
Method of String
Find sub-string
>>> n= ' ning si de shu de ' >>> n.find (' de ') 8>>> n.find (' Dee ') -1>>> n.find (' de ', 9,16) #范围包含第一个索引不包含第二个-1
Join is the inverse method of the split method
>>> s=[' 1 ', ' 2 ', ' 3 ', ' 4 ']>>> q.join (s) ' 1+2+3+4 ' >>> p= ', ' usr ', ' bin ', ' env ' >>> '/' . Join (P) '/usr/bin/env ' >>> print ' C: ' + ' \ \ '. Join (P) C:\usr\bin\env
Lower the lowercase master that returns a string
>>> ' My name is Ningsideshu '. Lower () ' My name was Ningsideshu ' >>> if ' name ' in [' my ', ' name ', ' is ']:p rint ' F Ound it! ' >>> if ' my ' in [' my ', ' Name ', ' is ']:p rint ' Found it! ' Found it!
Replace replacement
>>> ' This was a pen '. Replace (' pen ', ' apple ') ' This is a apple '
Split splits a string into a sequence
>>> ' 1+2+3+4+5 '. Split (' + ') [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ']>>> '/usr/bin/env '. Split ('/') [', ' usr ', ' bin ', ' Env ']>>> ' using the default '. Split () #默认所有空格作为分隔符 (spaces, line breaks, etc.) [' using ', ' the ', ' Default ']
Strip returns a string that removes spaces (or specified characters) on both sides (in addition: Lstrip,rstrip)
>>> ' My name is NSDs '. Strip () ' My name is NSDs ' >>> ' *my name was NSDs * '. Strip (' * ') ' My name is Ns ds
Translate substitution, unlike replace, can replace a single character (some part of a string)
>>> from string import maketrans>>> N=maketrans (' ns ', ' MF ') >>> ' My name is Ningsideshu '. Translate (n) ' My mame if Mimgfidefhu ' >>> ' My name is Ningsideshu '. Translate (n, ' M ') #第二个参数指定需要删除的字符 ' y mame if mimg Fidefhu '
Template string
>>> from string import template>>> s=template (' $x. Name $x! ') >>> s.substitute (x= ' hello ') ' Hello. Name Hello! ' >>> s=template ("It ' t ${x}tastic!") >>> S.substitute (x= ' Slurm ') "It ' t slurmtastic!" >>> s=template ("It ' t ${x}tastic${y}!") >>> S.substitute (x= ' Slurm ', y= ' a ') "It ' t slurmtastica!" >>> s=template (' A $thing must never $action. ') >>> d={}>>> d[' thing ']= ' gentleman ' >> > d[' action ']= ' show his socks ' >>> s.substitute (d) ' A gentleman must never show his socks. '