首页 > 代码库 > python字符串

python字符串

str:字符串

str.capitalize()首字母变大写:

>>> ret="nanhua"
>>> s=ret.capitalize()
>>> s
‘Nanhua‘

str.center()指定字符串左右居中(可指定长度及填充字符,默认空格):

>>> ret="nanhua"
>>> s=ret.center(20)
>>> s
‘       nanhua       ‘
>>> s1=ret.center(20,"@")
>>> s1
‘@@@@@@@nanhua@@@@@@@‘

 

str.count():计算子序列的个数(子序列在字符串中出现的次数)(可指定范围):

>>> ret="something for nothing"
>>> s=ret.count("th")
>>> s
2
>>> s=ret.count("th",0,10)
>>> s
1

 

str.endswith():检测字符串是否以指定子序列结尾(可指定范围):

>>> ret="lost in world"
>>> s=ret.endswith("ld")
>>> s
True
>>> s1=ret.endswith("in",3,8)
>>> s1
False
>>> s1=ret.endswith("in",3,7)
>>> s1
Tru

str.startswith():检测字符串是否以指定子序列开始(可指定范围):

>>> ret="lost in world"
>>> s=ret.startswith("lost")
>>> s
True
>>> s1=ret.startswith("s",2,4)
>>> s1
True

 

str.expandtabs():将tab键转换为空格(\t:默认八个空格,可指定):

>>> ret="lost\tin\tworld"
>>> ret
‘lost\tin\tworld‘
>>> s=ret.expandtabs()
>>> s
‘lost    in      world‘
>>> s1=ret.expandtabs(10)
>>> s1
‘lost      in        world‘

 

str.find():找到第一个指定子序列的索引(找不到返回-1):

>>> ret="lost in world"
>>> s=ret.find("o")
>>> s
1
>>> s=ret.find("o",3,10)
>>> s
9
>>> s=ret.find("!")
>>> s
-1

rfind() 

 

str.format():字符串的格式化:

>>> ret="Hello {0}  interest {1}"
>>> new1=ret.format("Nanhua","computer")
>>> ret
‘Hello {0}  interest {1}‘

>>> new1
‘Hello Nanhua  interest computer‘

{0},{1}:可作为占位符,只能从0开始

 

str.index():寻找子序列的位置,找不到就报错:

>>> ret="lost in world"
>>> s=ret.index("o")
>>> s
1
>>> s=ret.index("o",3,10)
>>> s
9
>>> s=ret.index("!")
Traceback (most recent call last):
  File "<pyshell#235>", line 1, in <module>
    s=ret.index("!")
ValueError: substring not found

 

rindex()

 

isalnum()判断是否是字母或数字

isalpha()判断是否都是字母

isdigit()判断是否都是数字

islower()判断是否小写

isupper()判断是否大写

isspace()是否空格

istitle()是否标题

 

join():

>>> li=["a","b","c","d","e"]
>>> "&".join(li)
‘a&b&c&d&e‘

 

>>> li=("a","b","c","d","e")
>>> "&".join(li)
‘a&b&c&d&e‘

 

ljust()内容左对齐,右侧填充内容:

rjust()内容右对齐,左侧填充内容:

>>> s.rjust(20)
‘           nanhua   ‘
>>> s="nanhua"
>>> s.rjust(20)
‘              nanhua‘
>>> s.ljust(20)
‘nanhua           

 

lstrip()去掉左边空格:

rstrip()去掉右边空格:

strip()去掉左右两边空格:

>>> s="  nanhua  "
>>> s.lstrip()
‘nanhua  ‘
>>> s.rstrip()
‘  nanhua‘
>>> s.strip()
‘nanhua‘

 

str.partition()根据找到的第一个指定子序列分成元祖:

>>> s="lost in world"
>>> s.partition("o")
(‘l‘, ‘o‘, ‘st in world‘)

 

str.replace()替换子序列:

>>> s="no problem"
>>> s.replace("o","s")
‘ns prsblem‘

 

split()根据指定子序列分割字符串:

>>> s="lost in world"
>>> s.split("o")
[‘l‘, ‘st in w‘, ‘rld‘]

 

swapcase()大小写互换:

>>> s="Nanhua"
>>> s.swapcase()
‘nANHUA‘

 

str.title()转换为标题:

>>> s="lost in world"
>>> s.title()
‘Lost In World‘

 

str.upper()变大写:

str.lower()变小写:

>>> s="NanHua"
>>> s.upper()
‘NANHUA‘
>>> s.lower()
‘nanhua‘

python字符串