python字符串--常见操作

 1 myStr = "hello world by ksunone" 

find()

find 检测 str 是否包含在 mystr中,如果是返回开始的索引值,否则返回-1 (从左到右寻找)
rfind 从右到左寻找
mystr.find(str, start=0, end=len(mystr)) #范围区间 “左闭右开”

1 print(myStr.find("o")) #返回4
2 # 在[0,5)的区间 寻找“ ”
3 print( myStr.find(" ", 0, 5))  # 找不到,返回 -1
View Code

index()

index 跟find()方法一样,只不过如果str不在 mystr中会报一个异常.
一般用find 不用 index
mystr.index(str, start=0, end=len(mystr))

1 # print(myStr.indx("abc")) 找不到  报错 'str' object has no attribute 'indx'
View Code

count()

count 返回 str在start和end之间 在 mystr里面出现的次数

1 mystr.count(str, start=0, end=len(mystr))

replace()

replace 把 mystr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次.

1 mystr.replace(str1, str2, mystr.count(str1))

split()

split 以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串

1 mystr.split(str, maxsplit=2)

capitalize()

capitalize 把字符串的第一个字符大写

mystr.capitalize()

title()

title 把字符串的每个单词首字母大写

 print(myStr.title()) #输出Hello World By Ksunone

lower()

lower 转换 mystr 中所有小写字符为大写

 mystr.lower() #输出 HELLO WORLD BY KSUNONE

upper()

将字符串的大写转换为小写

myStr.lower() #输出  helle world by ksunone

ljust()

ljust 返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串

myStr.ljust(60,".')  #输出hello world by ksunone......................................

rjust()

rjust 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串.

myStr.rjust(60,".") #输出 ......................................hello world by ksunone

center()

center 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串

myStr.center(60, '.') #输出 ...................hello world by ksunone...................

lstrip()   rstrip()   strip()

lstrip 删除 mystr 左边的空白字符
rstrip 删除 mystr 字符串末尾的空白字符
strip 删除mystr字符串两端的空白字符

"  hello world  ".lstrip()  #---》"helle wrold  ”
"  hello world  ".rstrip()  #---》“  helle wrold"
“  hello world  ”.strip()  #---》 “helloworld”

partition()

partition 把mystr以str分割成三部分,str前,str和str后 (从左到右)
rpartition 从右到左

myStr.partition("o") #---> ('hell', 'o', ' world by ksunone')
myStr.rpartition("o") #--->('hello world by ksun', 'o', 'ne')

splitlines()

splitlines 按照行分隔( ),返回一个包含各行作为元素的列表

"hello
world".splitlines() #--->['hello', 'world']

isalpha()

isalpha 如果 mystr 所有字符都是字母 则返回 True,否则返回 False

 '124aaa'.isalpha()  #---> False
 'aaa'.isalpha()   #----> True

isdigit()

isdigit 如果 mystr 只包含数字则返回 True 否则返回 False.

 '124aaa'.isdigit()  #--->False
 '123'.isdigit() #---> True

isalnum()

isalnum 如果 mystr 所有字符都是字母或数字则返回 True,否则返回 False

'123.151'.isalnum()  #---> False
'123abc'.isalnum()  #----> True

isspace()

isspace 如果 mystr 中只包含空格,则返回 True,否则返回 False.

 '123abc'.isspace()  #-->False
 '  '.isspace()  #-->True

join()

join mystr 中每个字符后面插入str,构造出一个新的字符串

 "_".join(myStr) #-->h_e_l_l_o_ _w_o_r_l_d_ _b_y_ _k_s_u_n_o_n_e
 "/".join(["hello", "world", "by", "ksunone"]) #-->hello/world/by/ksunone
原文地址:https://www.cnblogs.com/ksunone/p/8488222.html