python中的字符串的种种函数

时间:2023-03-09 19:21:09
python中的字符串的种种函数

1.连接list;为了将任意包含字符串的 list 连接成单个字符串,可以使用字符串对象的 join 方法.

join 只能用于元素是字符串的 list;它不进行任何的强制类型转换。连接一个存在一个或多个非字符串元素的 list 将引发一个异常。

examples:

>>> music = ["Abba","Rolling Stones","Black Sabbath","Metallica"]

>>> print music

['Abba', 'Rolling Stones', 'Black Sabbath', 'Metallica']

Join a list with an empty space

>>> print ' '.join(music)

Abba Rolling Stones Black Sabbath Metallica

Join a list with a new line

>>> print "\n".join(music)

Abba

Rolling Stones

Black Sabbath

Metallica

Join a list with a tab

>>> print "\t".join(music)

Abba Rolling Stones Black Sabbath Metallica

>>>

2.分割字符串:anystring.split(delimiter, 1) 是一个有用的技术,在您想要搜索一个子串,然后分别处理字符前半部分 (即 list 中第一个元素) 和后半部分 (即 list 中第二个元素) 时,使用这个技术

examples:

x = 'blue,red,green'

x.split(",")

['blue', 'red', 'green']

>>> 

>>> a,b,c = x.split(",")

>>> a

'blue'

>>> b

'red'

>>> c

'green'

Let's show one more example. 

>>> word = "This is some random text"

>>> words = word.split(" ")

>>> words

['This', 'is', 'some', 'random', 'text']

3.与string相关的正则表达式。