python 字符串操作

来源:互联网 发布:机械设计自动画图软件 编辑:程序博客网 时间:2024/06/05 03:31

查找   find检测str是否在Sstr中,如果是返回开始的索引值,否则返回-1

Sstr="hello world!!!"str="hello"Sstr.find(str)Sstr.find("hi")

count 返回str在start和end之间在Sstr出现的次数

Sstr.count(str,start=0,end=len(Sstr)) Sstr="hello world"Sstr.count("o")Sstr.count("o",2,5)

字符串替换 replace

把Sstr中的str1替换成str2,如果有多个str1,则可以用count指定替换次数

##    格式   Sstr.replace(str1,str2,Sstr.count(str1))   Sstr="hello world"  print(Sstr.replace("l","L"))print(Sstr.replace("l","L",2))        ## 但是Sstr本身并没有被替换,可打印Sstr来查看## 用一个新的字符串来接收替换后的字符串NewStr=Sstr.replace("l","L",2)

分隔字符串 split

以str为分隔符切片Sstr,用count来显示要分隔的次数

Sstr="hello world!!!"print(Sstr.split("l"))print(Sstr.split("l",2))

capitalize 字符串首字母大写,title字符串所有单词大写

Sstr="never is impossible"print(Sstr.capitalize())print(Sstr.title())

startswith 检查字符是否是以str开头,返回值为true或者false
endswith 检查字符是否是以str结尾,返回值为true或者false

Sstr="hello world!!!"str1=("he")print(Sstr.startswith(str1))str2="!!!"print(Sstr.endswith(str2))

lower 将字符串中的字母全部转化为小写
upper 将字符串中的字符全部转化为大写

Sstr="hello world!!!"str1=("he")print(Sstr.startswith(str1))str2="!!!"print(Sstr.endswith(str2))

lstrip 删除str左边的空白字符
rstrip 删除str右边的空白字符
strip 删除str两端的空白字符

print(Sstr.lstrip())print(Sstr.rstrip())print(Sstr.strip())

partition 把Sstr以str分成三部分,str前,str,str后
rpartition 同上,但是从右往左找str

Sstr="I want to win"print(Sstr.partition("to"))


splitlines  按行分割,返回一个包含各行作为元素的列表

str3="hello\nworld"print(str3.splitlines())

isalpha 如果所有字符都是字母,则返回true,否则返回false
isdigit 如果所有字符都是数字返回true,否则返回false
isalnum 若所有字符都是字母或者数字返回true,否则返回false
isspace 若所有字符都是空格,则返回true,否则返回false


join  在一个列表line中的每个字符后面插入str,构成一个新的字符串

str=" "line=["恭喜","RNG"]print(str.join(line))