字符串常用操作

  • capitalize()

 

name = "my name is he gui cheng"
print(name.capitalize())#使字符串首字母大写

  

 

  • count()
name = "my name is he gui cheng"
print(name.count("h"))#统计h在字符串上的数量

  

  • center()
name = "my name is he gui cheng"
print(name.center(50,"-"))#打印50个字符,不够的用-补上

  

  • endswith()
name = "my name is he gui cheng"
print(name.endswith('ng'))#判断字符串是否已ng结尾,是则True,否则False

  

  • expandtabs()
name = "my name \tis he gui cheng"
print(name.expandtabs(tabsize=30))#将tab键转换为30个空格

  

  • find()
name = "my name \tis he gui cheng"
print(name.find('name'))#返回查找字符串name开头字母所在索引,n在字符串的第三位,所以返回3
print(name[name.find('name'):])#字符串也能切片,从索引第三位开始到最后

 

    

  • format()
name = "my name is {name},age is {age}"
print(name.format(name="heguicheng",age=27))#格式化

  

  • isalnum()
print("ab123".isalnum())#判断字符串是否只包含阿拉伯字符

  

  • isalpha()
print("abcd".isalpha())#判断字符串是否是纯英文字符串

  

  •  isdecimal()
print("12345677".isdecimal())#判断字符串是否是纯十进制数字

  True

  • isdigit()
print("1234".isdigit())#判断字符串是否是一个整数

  True

  • isidentifier()
print("1A".isidentifier())#判断是否是一个合法的标识符(变量名)

  False

  • islower()
print("avc".islower())#判断字符串是否是小写英文字母

  True

  • istitle()
name = "my name is {name},age is {age}"
print(name.istitle())#判断是否符合title格式,每个单词首字母需要为大写字母

  False

  • isupper()
print("AAA".isupper())#判断字符串是否全是大写英文字母

  True

  • join
print("+".join(['1','2','3']))#将+号加入到列表上数据的连接

  

  • ljust()
print(name.ljust(50,"*"))#保证输出50个字符,不够用*补充

  

  • rjust()
print(name.rjust(50,"-"))#保证输出50个字符,不够用*补充

  

  • lower()
print("GuiCheng".lower())#把字符串里面的大写英文字母改为小写

  

  • upper()
print("GuiCheng".upper())#把字符串里面的小写英文字母改为大写

  

  • lstrip()
print("\nguicheng".lstrip())#去掉字符串左边的回车、空格

  

  • rstrip()
print("guicheng\n".rstrip())#去掉字符串右边的回车、空格

  

  • strip()
print("     guicheng\n".strip())#去掉字符串两边的回车、空格

  

 

  • maketrans()
  • translate()
p = str.maketrans("abcdefgh","12345678")#将两个字符串对等关联,与之使用传递的时候,右边的替代左边的
print("heguicheng".translate(p))

  

  • replace()
print("heguicheng".replace("h","H"))#用H替换所有的h
print("heguicheng".replace("h","H",1))#用H替换第一个h

  

  • rfind()
print("heguicheng".rfind("e"))#返回右侧第一个e的索引序号

  

  • split()
print("he gui cheng".split())#默认已空格将字符串分离加入列表
print("1+2+3+4".split("+"))#已+号分割字符串分离加入列表

  

  • swapcase()
print("hEgUIcHENG".swapcase())#将字符串大小写互相转换

  

  • title()
print("he gui cheng".title())#将字符串首字母改为大写

  

 

posted @ 2017-11-29 21:31  雨之愿风  阅读(174)  评论(0编辑  收藏  举报