1.find()
find方法可以在一个较长的字符串查找子串。它返回子串所在的位置的最左端索引。如果没有找到则返回-1.
>>> 'hello mtbaby'.find('mt')
6
>>> s = 'hello python'
>>> s.find('hello')
0
>>>
注意:字符串的find方法并不返回布尔值。如果返回的是0,则证明在索引0位置找到了子串。
2.join()
join方法是非常重要的字符串方法,它是split方法的逆方法,用来连接序列中的元素:
s = ['1','2','3','4']
ss = '+'
l = ss.join(s)
print l
输出:
1+2+3+4
s = [1,2,3,4]
ss = '+'
l = ss.join(s)
print l
输出:
Traceback (most recent call last):
File "F:/MTbaby/smalltest.py", line 12, in <module>
l = ss.join(s)
TypeError: sequence item 0: expected string, int found
可以看到,需要被连接的序列元素都必须是字符串。
3.lower()
lower方法返回字符串的小写字母。
s = 'HHHHHH'
print s.lower()
输出:
hhhhhh
4.replace()
replace方法返回某字符串的所有匹配项均被替换之后得带字符串。
s = 'hello my name is MTbaby'
h = s.replace('hello','hi')#将字符串s中的'hello'替换成'hi'
print h
输出:
hi my name is MTbaby
5.split()
这是一个非常重要的字符串方法,它是join的逆方法,用来将字符串分割成序列。
s = '1+2+3+4'
l = s.split('+')
print l
输出:
['1', '2', '3', '4']
注意:如果不提供任何分隔符,程序会把所有空格作为分隔符(空格,制表,换行等)
s = 'hello my name is'
l = s.split()
print l
输出:
['hello', 'my', 'name', 'is']
6.strip()
strip方法返回去除两侧(不包括内部)空格的字符串。
s = ' hello my name is '
l = s.strip()
print l
输出:
hello my name is
7.translate()
translate方法和replace方法一样,可以替换字符串中的某些部分,但是和前者不同的是,translate方法只处理单个字符。它的优势在于同时进行多个替换,有些时候比replace效率搞得多。