python 常用的字符串处理函数

find()  

功能:检测字符串是否包含特定字符,如果包含,则返回开始的索引;否则返回-1

复制代码
## find()函数
str = 'hello world'
# 'wo'在字符串中
print( str.find('wo') )
# 'wc'不在字符串中
print( str.find('wc') )
## 输出:
##     6
##     -1
View Code
复制代码

 

index()

功能:检测字符串是否包含指定字符串,如果包含,则返回开始的索引值,否则提示错误

复制代码
## index()函数
str = 'hello world'
# 'wo'在字符串中
print( str.index('wo') )
# 'wc'不在字符串中,程序报错ValueError,终止运行
print( str.index('wc') )
## 输出:
##     6
##     ValueError: substring not found
View Code
复制代码

 

count()

功能:返回str1在string中指定索引范围内批[start,end]出现的次数

复制代码
## count()函数
str = 'hello world'
# 统计str中全部字母l的个数
print( str.count('l') )
# 统计str中从第5+1个字母到最后一个字母中,字母l的个数
print( str.count('l', 5, len(str)) )
## 输出:
##     3
##     1
View Code
复制代码

 

replace()

语法:str1.replace(str2,count)

功能:将str1中的str1替换成str2,如果指定count,则不超过count次

复制代码
## replace()函数
print('=*'*10, 'replace()函数', '=*'*10)
str = 'hello world hello world'
str1 = 'world'
str2 = 'waltsmith'
# 将所有的str1替换为str2
print( str.replace(str1, str2) )
# 只将前1个str1替换为str2
print( str.replace(str1, str2, 1) )
## 输出:
##     hello waltsmith hello waltsmith
##     hello waltsmith hello world
View Code
复制代码

 split()

语法:

str.split('分界符',maxSplit)  naxSplit默认值为-1,表示根据定界符分割所有能分割的,返回值为列表

功能:

如果maxsplit有指定值,则仅分割maxsplit个子字符串

复制代码
## split()函数
str3 = 'I am a good boy!'
# 以空格分割字符串,分界符默认为空格
print(str3.split(' ', 3))
# 以字母o作为分界符,指定最大分割为2,将返回最大分割+1个元素的列表
print(str3.split('o', 2))

## 输出:
##     ['I', 'am', 'a', 'good boy!']
##     ['I am a g', '', 'd boy!']
View Code
复制代码

 capitalize()

语法:str.capitalize()

功能:将字符串的首字母大写,其余字母全部小写

复制代码
## capitalize()函数
str4 = 'I aM waLt smith'
# 字符串的首字母大写,其余字母全部小写
print(str4.capitalize())
## 输出:
##     I am walt smith
View Code
复制代码

title()

语法:str.title()

功能:将字符串中所有单词的首字母大写,其余字母全部小写

复制代码
## title()函数
# 正常字符串的转换
str5 = "I am walt smith!"
print(str5.title())
## 输出:
##     I Am Walt Smith!
# 字符中包含标点符号
str6 = "I'm walt-sMith!"
print(str6.title())
## 输出:
##    I'M Walt-Smith!
View Code
复制代码

 

posted @   百因必有果  阅读(131)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示