脑课堂编程教育

python 字符串常用函数详解

Python 4年前
53 0 0
脑课堂编程培训

字符串常用函数:

声明变量

str="Hello World"

find() 检测字符串是否包含,返回该字符串位置,如果不包含返回-1

str.find("Hello") # 返回值:0
str.find("W") # 返回值:6, 这里需要注意下:空格也是一个字符。W前面有个空格,所以W位置是6
str.find("R") # 返回值:-1,并不包含在Hello World中,如果不包含返回-1

index() 检测字符串是否包含指定的字符,并返回开始的索引值,如果不包含会报错

str.index("Hello") # 返回值:0
str.index("o") # 返回值:4
str.index("W") # 返回值:6
str.index("R") # 返回值:报错信息 ,因为R并不包含其中。 所以建议慎用,如果值不存在程序报错就完蛋了。

len() 返回字符串长度,以0开始计算

len(str) #返回值:10

count() 收集指定字符在字符串中出现的次数

str.count("o") 返回值:2, o字符在Hello World中存在两个。

# 也可以指定count()函数从某个位置开始查找。 语法为:count(" ",start,end)
str.count('o',5,10) 返回值:1, 原因:指定位置后会从索引5开始检索,以索引10结束。 5到10之间只存在一个'o'
str.count('o',4,len(str)) 返回值: 2,索引从4开始,到字符串结束。len(str)字符串长度

replace() 替换字符串

str.replace('hello','HELLO')  # 把小写的hello替换为大写的HELLO
str.replace('W','B')  # 把W替换为B

split() 字符串切割

str.split('o') #以列表的形式返回["hell","w","rld"] ,hello world 里面的o被切割掉

upper() 将所有的字符转换为大写

str.upper() #返回值为 HELLO WORLD

title() 首字母转换为大写

str.title() #返回值:Hello World

center() 返回一个原字符串居中,并以空格填充至长度宽度的新字符串

str.center(80) #返回值: ( Hello World ) 其字符串两头被空格填充

join() 在字符串后面插入一个指定字符,构造一个新的字符串

_str="_" 
list=["I","Love","You"]
_str.join(list) # 返回值: I_Love_You 每个列表元素后面都插入一个下划线

isspace() 检测字符串中是否只包含空格,如果有返回Trun反之返回False,通俗的讲就是判断非空验证

str=" "
strOne="早上好!"
str.isspace() # 返回trun
strOne.isspace #返回false

isalnum() 检测是否只包含数字或字母。用处:可以用于判断密码,一般情况下密码不能输入汉字或空格。

strOne="a123"
strTwo="a 456"
strOne.isalnum() # 返回trun
strTwo.isalnum() # 返回false ,因为包含空格

isdigit() 检测字符是否只包含数字, 返回Trun 和 False

str='123'
strone='a123'
str.isdigit() 返回trun 
str.isdigit() 返回false

isalpha() 检测字符串是否只包含字母

str="abcd"
strone="123abacd"
str.isalpha() # 返回 trun
strone.isalpha() # 返回false
收藏

本文标题:python 字符串常用函数详解

本文链接:https://naoketang.com/p/px0qe12m526v

评论区

推荐课程