Python字符串中常用的方法

字符串格式化

使用字符串格式化操作符(%)来实现:

>>> format = "Hello %s,nice to meet you!"
>>> print format % 'Jack'
Hello Jack,nice to meet you!
>>> format = "Hello %s,nice to meet %s!"
>>> print format % ('Rose','me')
Hello Rose,nice to meet me!

格式化多个值可以使用元组或字典。%后面的s表示格式化为字符串,还有其他的如下:

模板字符串
string提供了另一种格式化值的方法:

>>> from string import Template
>>> s = Template("$x,glorious $x!")
>>> s.substitute(x='jack')
'jack,glorious jack!'

还可以使用字典变量提供值/名称对:

>>> 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.'

字符串方法

find

类似于java中的indexOf。在字符串中查找子串。返回子串第一次出现在字符串中的索引,没找到返回-1。

>>> s = "hello,it's me me"
>>> s.find('me')
11

find还可以接收可选的起始点和结束点:

>>> s = "hello,it's me me"
>>> s.find('me')
11
>>> s.find('me',12) #提供了起点
14

split

用于将字符串分割成序列

>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> "nice to meet you".split() #不提供参数则以所有空格(包括制表和换行)作为分隔符
['nice', 'to', 'meet', 'you']

join

join方法是split的逆方法,用来连接序列中的元素:

>>> seq = [1,2,3,4,5]
>>> sep = '+'
>>> sep.join(seq)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>> seq = list('12345')
>>> seq
['1', '2', '3', '4', '5']
>>> sep.join(seq)
'1+2+3+4+5'

注意是参数是序列,且需要连接的序列元素都必须是字符串。

replace

用来替换字符串

>>> 'This is a test'.replace('is','eez')
'Theez eez a test'

strip

类似java中的trim方法。用来去掉字符串的两侧空格

>>> ' yeah I love her        '.strip()
'yeah I love her'

也可以指定需要去除的字符,但是也只是去除两侧的字符:

>>> "*** Mother fu*k ,fu*k you!***".strip('*!')
' Mother fu*k ,fu*k you' #参数里面没有指定空格,因此左边还有一个空格

translate

这个方法类似replace方法,但是translate方法只处理单个字符,优势在于可以同时进行多个替换,有时候效率比replace高的多。

猜你喜欢

转载自blog.csdn.net/yjw123456/article/details/78663152