欢迎访问宙启技术站
智能推送

Python中的字符串函数:split(),join()等详解

发布时间:2023-06-02 07:28:29

Python中的字符串是不可改变的序列,提供了许多的字符串函数来处理字符串的操作。

1. 字符串分割函数 split()

字符串分割函数被用来将一个字符串切分成子串,它的具体语法是:

str.split(sep=None, maxsplit=-1)

其中:

- str:指定需要分割的字符串;

- sep:指定字符串的分隔符,默认为 None;

- maxsplit:最多分割次数,默认 -1,不限制分割次数。

使用实例:

s = "this is a text"
s.split() # 返回['this', 'is', 'a', 'text']
s.split('is') # 返回['th', ' ', ' a text']
s.split('s', 1) # 返回['thi', ' is a text']

2. 字符串合并函数 join()

字符串合并函数被用来将一个列表中的子串合并成一个字符串,它的具体语法是:

str.join(iterable)

其中:

- str:指定合并的字符串;

- iterable:指定需要合并的列表。

使用实例:

s = ['this', 'is', 'a', 'text']
str = ','.join(s) # 返回"this,is,a,text"

3. 字符串查找函数 find(), index() 和 count()

(1)find()函数:在一个字符串中查找子串 次出现的位置。

s.find(sub[, start[, end]])

其中:

- sub:需要查找的字符串;

- start:开始查找的位置,默认为 0;

- end:结束查找的位置,默认为字符串的长度。

使用实例:

s = "this is a text"
idx = s.find('is') # 返回2
idx = s.find('is', 3, 7) # 返回-1

(2)index()函数:与 find() 函数相同,但如果子串不存在,则会抛出异常。

s.index(sub[, start[, end]])

其中:

- sub:需要查找的字符串;

- start:开始查找的位置,默认为 0;

- end:结束查找的位置,默认为字符串的长度。

使用实例:

s = "this is a text"
idx = s.index('is') # 返回2
idx = s.index('is', 3, 7) # 抛出异常

(3)count()函数:统计子串在字符串中出现的次数。

s.count(sub[, start[, end]])

其中:

- sub:需要查找的字符串;

- start:开始查找的位置,默认为 0;

- end:结束查找的位置,默认为字符串的长度。

使用实例:

s = "this is a text"
count = s.count('is') # 返回2
count = s.count('is', 3, 7) # 返回0

4. 字符串替换函数 replace()

字符串替换函数被用来将一个子串替换成另一个子串,它的具体语法是:

str.replace(old, new[, count])

其中:

- old:需要被替换的子串;

- new:替换成的子串;

- count:需要替换的次数,默认为-1,表示全部替换。

使用实例:

s = "this is a text"
s_new = s.replace('is', 'was') # 返回"thwas was a text"
s_new = s.replace('is', 'was', 1) # 返回"thwas is a text"

5. 字符串大小写转换函数 lower() 和 upper()

(1)lower()函数:将字符串转换成小写。

s.lower()

使用实例:

s = "THIS IS A TEXT"
s_new = s.lower() # 返回"this is a text"

(2)upper()函数:将字符串转换成大写。

s.upper()

使用实例:

s = "this is a text"
s_new = s.upper() # 返回"THIS IS A TEXT"

6. 字符串删除空格函数 strip()

字符串删除空格函数被用来删除字符串中的空格,它的具体语法是:

s.strip([characters])

其中:

- characters:指定需要删除的字符,默认为空格。

使用实例:

s = "    this is a text     "
s_new = s.strip() # 返回"this is a text"
s_new = s.strip('t') # 返回"    this is a ex    "