python 字符串操作常用操作,如字符串的替换、删除、截取、赋值、连接、比较、查找、分割等
今天挑几个经常用的进行实操,需要其他的操作就去度娘查看哈
用法说明
- 查找
str.index 和str.find 功能相同,区别在于find()查找失败会返回-1,不会影响程序运行。一般用find!=-1或者find>-1来作为判断条件
a='hello world'
a.find('l')
结果:2
- 切片
L=[1,2,3,4,5,6,7,8]
L[0:3]
结果:[0,1,2]
L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,正好是3个元素
- 按输入字符分割
s="alexalec"
ret=s.split("e")
输出结果:['al', 'xal', 'c']
- 替换
s="alex RT alex"
s.replace("al","BB")
输出结果: BBex RT BBex
具体实操例子
代码如下:
str1 = 'python 字符串操作常用操作,如字符串的替换、删除、截取、赋值、连接、比较、查找、分割等'
#在str1中提取python字符
p_str_1 = str1.find("p")
n_str_1 = str1.find("n")
if p_str_1 != -1 and n_str_1 != -1:
print(str1[p_str_1: n_str_1 + 1])
#取出“替换、删除、截取、赋值、连接、比较、查找、分割"
a_str_2 = str1.find("替换")
b_str_2 = str1.find("等")
if a_str_2 != -1 and b_str_2 != -1:
result1 = str1[a_str_2: b_str_2]
#遇到顿号,进行切割
result2 = result1.split("、")
#使用替换,将顿号去掉
result3 = result1.replace("、", "")
查看结果: