python字符串常用函数

39 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第22天,点击查看活动详情


大家好,我是芒果,一名非科班的在校大学生。对C/C++、数据结构、Linux及MySql、算法等领域感兴趣,喜欢将所学知识写成博客记录下来。 希望该文章对你有所帮助!如果有错误请大佬们指正!共同学习交流

作者简介:



string 模块常用函数

  • Python标准库提供了string模块, 包含了很多非常方便实用的函数

注意点:记得字符串是不可变对象, 只能生成新字符串

image-20220319153446313

image-20220319153454157


image-20220319153507776


image-20220319153514842


image-20220319153520363


string 模块常用函数

  • Python标准库提供了string模块, 包含了很多非常方便实用的函数

注意点:记得字符串是不可变对象, 只能生成新字符串

image-20220319153446313

image-20220319153454157


image-20220319153507776


image-20220319153514842


image-20220319153520363


join函数

将序列中的字符串合并成一个字符串. join函数

a = ['aa','bb','cc']
b = ' '.join(a)
print(b)    #aa bb cc

split函数

按空格将字符串分割成列表 split函数

a = 'aa bb cc'
b = a.split(' ')
print(b)    #['aa', 'bb', 'cc']

通常和join函数一起使用

a = 'aaa,bbb,ccc'
b = a.split(',') #以,分割成列表
print(b)
print(';'.join(b)) #分号连接
print('hello'.join(b))
​
#执行结果:
['aaa', 'bbb', 'ccc']
aaa;bbb;ccc
aaahellobbbhelloccc

\

startswith函数 和 endswith函数

判定字符串开头结尾 startswith函数 和 endswith函数

a = 'hello world'
print(a.startswith('h'))    #True
print(a.startswith('hee'))  #False
print(a.endswith('d'))      #True

\