from string import Template
find返回最左端索引,没有-1
>>> 'with moo-moo here'.find('moo')
5
>>> 'with moo-moo here'.find('mooo')
-1
可选起始点和结束点,包含第一个index,不包括第二个index,和切片一样。
>>> sub = '$$$ Get rich now!!! $$$'
>>> sub.find('$$$')
0
>>> sub.find('$$$', 1)
20
>>> sub.find('!!!', 1)
16
>>> sub.find('!!!', 0, 16)
-1
>>>
join是split的逆方法。每项必须是str
>>> seq=[1,2,3,4,5]
>>> sep='+'
>>> sep.join(seq)
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
sep.join(seq)
TypeError: sequence item 0: expected string, int found
>>> seq=['1','2','3','4','5']
>>> sep.join(seq)
'1+2+3+4+5'
>>> dirs = '','usr','bin','env' 第一个什么也没有,下面就没有。如果是有一个 空, 下面就空。
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print 'C:' + '\\'.join(dirs)
C:\usr\bin\env
>>>
>>> 'Tero EWED eTBwqq'.lower()
'tero ewed etbwqq'
>>> "that's all folks".title()
"That'S All Folks"
>>> import string
>>> string.capwords("that's all folks")
"That's All Folks"
>>> 中间有需要小写的冠词,自己想办法了。
>>> 'This is a test'.replace('is', 'eez')
'Theez eez a test'
split是join的逆方法
>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env'] # 前面有个空,里面啥也没有
>>> 'usr/bin/env'.split('/')
['usr', 'bin', 'env']
>>> '/usr/bin/env/'.split('/')
['', 'usr', 'bin', 'env', '']
>>> 'using default the'.split() 默认所有空格作为分隔符(空格,指标,换行)
['using', 'default', 'the']
>>>
strip返回去除两侧的字符串
>>> ' internal whitespace is kept '.strip()
'internal whitespace is kept'
可以指定要去除的
>>> '*** spam * for * everyone!!! ***'.strip('*!') 这里没有空格, 下面的空格去不掉
' spam * for * everyone!!! '
>>> '*** spam * for * everyone!!! ***'.strip(' *!')这里有空格, 下面的空格去掉
'spam * for * everyone'
>>> 所以,如果strip有东西,那空格就不默认了。
translate和replace很像,不过只能处理单个字符。但可以同事处理 多个 单个字符。同事替换,比replace效率高。
python3已经没有maketrans了。https://docs.python.org/3.3/search.html?q=maketrans&check_keywords=yes&area=default