python字符串中常用函数

微信扫一扫,分享到朋友圈

python字符串中常用函数
收藏 00

join方法

*string.join(seq)

以string作为分隔符,将seq中所有的元素合并为一个新的字符串

s1='你好啊'
ss = ['你','好','啊']
c = '#'.join(s1)
print(c)

执行结果

你#好#啊

join方法可以对列表、元组等数据类型里面的字符串进行合并。

replace方法

str.replace(old, new[, max])
  • old — 将被替换的子字符串。
  • new — 新字符串,用于替换old子字符串。
  • max — 可选字符串, 替换不超过 max 次
str = "this is string example....wow!!! this is really string"
#字符串中有4个is
s1 = str.replace("is", "was")
s2 = str.replace("is", "was", 3)
print(s1)
print(s2)

执行结果

thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string

strip方法

string.strip([obj]) 

默认删除string前后的空字符,obj可以指定删除的字符

注意:只要头尾包含有指定字符序列中的字符就删除

用法1:去前后空字符

#去前后空字符
txt = "     banana     "
x = txt.strip()
print(txt)
print(x)

用法2:删除首尾指定字符

str = '123456121'
print (str.strip('12'))

执行结果

3456

split方法

str.split(str="", num=string.count(str)).
  • str — 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
  • num — 分割次数。默认为 -1, 即分隔所有。
  • 返回分割后的字符串列表。
u = "https://www.99zyku.com"
#使用默认分隔符
s1 = u.split()
#以"."为分隔符
s2 = u.split('.')
#分割0次
s3 = u.split('.',0)
#分割一次
s4 = u.split('.',1)
#分割两次
s5 = u.split('.',2)
#分割两次,并取序列为1的项
s6 = u.split('.',2)[0]

 

一个热爱互联网的咸鱼

你也可能喜欢

发表评论

您的电子邮件地址不会被公开。 必填项已用 * 标注

提示:点击验证后方可评论!

插入图片

热门

    抱歉,30天内未发布文章!
返回顶部