程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-05(5)

python 字符串常用函数

发布于2019-09-11 13:58     阅读(1048)     评论(0)     点赞(1)     收藏(5)


字符串常用函数:

  • 声明变量
str="Hello World"
  • 1
  • find() 检测字符串是否包含,返回该字符串位置,如果不包含返回-1
str.find("Hello")  # 返回值:0
str.find("W")  # 返回值:6, 这里需要注意下:空格也是一个字符。W前面有个空格,所以W位置是6
str.find("R") # 返回值:-1,并不包含在Hello World中,如果不包含返回-1
  • 1
  • 2
  • 3
  • index() 检测字符串是否包含指定的字符,并返回开始的索引值,如果不包含会报错
str.index("Hello")  # 返回值:0
str.index("o")  # 返回值:4
str.index("W")  # 返回值:6
str.index("R")  # 返回值:报错信息 ,因为R并不包含其中。 所以建议慎用,如果值不存在程序报错就完蛋了。
  • 1
  • 2
  • 3
  • 4
  • len() 返回字符串长度,以0开始计算
len(str) #返回值:10
  • 1
  • 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)字符串长度
  • 1
  • 2
  • 3
  • 4
  • 5

replace() 替换字符串

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

split() 字符串切割

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

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

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

title() 首字母转换为大写

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

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

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

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

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

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

str=" "
strOne="早上好!"
str.isspace()  # 返回trun
strOne.isspace #返回false
  • 1
  • 2
  • 3
  • 4

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

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

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

str='123'
strone='a123'
str.isdigit()  返回trun  
str.isdigit()  返回false
  • 1
  • 2
  • 3
  • 4

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

str="abcd"
strone="123abacd"
str.isalpha()  # 返回 trun
strone.isalpha() # 返回false
  • 1
  • 2
  • 3
  • 4


所属网站分类: 技术文章 > 博客

作者:倒车请注意

链接:https://www.pythonheidong.com/blog/article/107205/517d39958d6a264e0c74/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

1 0
收藏该文
已收藏

评论内容:(最多支持255个字符)