Python字符串常用操作
一、字符串的切片
1.1、通过下标及下标范围取值
my_str = 'myNameIsTaichi' value1 = my_str[2] value2 = my_str[-5]
|
字符串分割,语法:string[end: step]
- start:头下标,以0开始
- end:尾下表,以-1开始
- step 步长
str = "abc-123-如果我是DJ你会爱我吗.mp4" print(str[0:7])
print(str[0:-9])
print(str[8:])
|
1.2、index方法:查找特定字符串的下标索引值
my_str = "%pokes$@163&.com*" value3 = my_str.index("pokes") print(value3)
|
注意:1是”pokes”起始下标,即p所在的下标位置
1.3、replace方法:字符串替换
语法:string.replace(“被替换的内容”,“替换后的内容”[,次数])
str2= "ithahahaaa and ithehehehe" new_str2 = str2.replace("it","pokes") print(new_str2)
str1 = "212、Python用replace()函数删除制定 符号" str2 = str1.replace('、', '') print(str2)
|
1.4、split方法:分割字符串
语法:string.split(‘分隔符’,次数)
str = "abc-123-如果我是DJ你会爱我吗.mp4" str = str.split('-') print(str) 结果:['abc', '123', '如果我是DJ你会爱我吗.mp4']
|
1.5、strip方法:去除字符串两端的空格和回车符
strip
两头 ,lstrip
头(left), rstrip
尾(right)。
去掉两头的空格,注意不包含中间的空格
str5= " heihei hehe haha " new_str5=str5.strip() print(new_str5)
s = " %pokes$@163&.com* "
ss = s.strip().strip("%").lstrip('$').rstrip().rstrip('*') print(ss)
s = ' <0.01% ' ss = s.strip().lstrip('<').rstrip('%') print(ss)
|
1.6、count方法,统计字符串中某字符出现的次数
str6= "heihei hehe haha" cishu = str6.count("he") print(cishu)
|
1.7、len统计字符串的长度
str6= "heihei hehe haha" num=len(str6) print(num)
|
1.8、find字符串查找
语法:string.find('要查找的字', [开始位置, 结束位置])
str = "abc-123-如果我是DJ你会爱我吗.mp4" str = str.find('DJ') print(str) 结果:12
|
1.9、join() 列表转字符串
二、字符串判断
2.1、判断字符串是否出现过
查询字母k是否出现,如果出现结果返回索引,没出现则返回-1
print("pokes".find("k")) print("pooes".find("k"))
print("k" in "pooes") print("k" in "pokes")
|
2.2 、判断是否以xxx开头
判断是否以xxx开头,返回布尔值
print("pokes".startswith("k")) print("kpokes".startswith("k"))
|
2.3、判断是否以xxx结尾
print("pokes".endswith("k")) print("kpokesk".endswith("k"))
|
2.4、判断字符串是否只包含数字
str_1 = "123" str_2 = "Abc" str_3 = "123Abc"
print(str_1.isdigit()) print(str_2.isdigit()) print(str_3.isdigit())
|
2.5、判断字符串中包含特殊符号
input_psd = input("请输入字符串")
string = "~!@#$%^&*()_+-*/<>,.[]\/" for i in string: if i in input_psd: print("您的输入包含特殊字符")
|
或者导入 python 内置模块 re
import re input_psd = input("请输入字符串") test_str = re.search(r"\W",input_psd) if test_str==None: print("没有没有真没有特殊字符") else: print("该文本包含特殊字符")
|
2.6、连续判断过滤字符串
有时候我们需要连续的判断
if "download_zh.png" not in str: if "actjpgs" not in str: pass
|
他不能写成:
if "download_zh.png" and "actjpgs" not in str: pass
|
可以写成这样
if "download_zh.png" not in str and "actjpgs" not in str: pass
|
但是如果过滤的字符串有N多个,这样就很痛苦。那么你可以:
将需要过滤掉的字符串写进一个list
filter_strings = ["download_zh.png", "actjpgs"] if not any(s in item for s in filter_strings): print("过滤条件满足")
|
2.7字符串字母大小写转换和判断
- capitalize,将字符串得第一个字符转换成大写
- title,每个单词得首字母大写
- istitle, 判断每个单词得首字母是否大写
- upper 全部转换成大写
- lower 全部转换成小写
message = 'zhaorui is a beautiful girl!'
msg = message.capitalize() print(msg)
msg = message.title() print(msg)
cmd = msg.istitle() print(cmd)
spokes = message.istitle() print(spokes)
msg = message.upper() print(msg)
msg = message.lower() print(msg) print(len(msg))
|
三、字符串比较
s1='abc' s2="abc"
print(s1 == s2) print(s1 is s2)
pokes1 = input('请输入:') pokes2 = input('请输入:')
print(pokes1 == pokes2)
|
四、过滤掉某个字符
过滤掉单个字符
str1 = "212、Python用replace()函数删除制定 符号" str2 = str1.replace('、','') print(str2)
|
过滤掉多个符号
def zifu(str, x, y, z): strin = str.replace(x, '') .replace(y, '').replace(z, '') print(strin)
zifu("pokes,@163.com,kkkkk", ",", ",", "163") ```·
```python print("POKES".lower()) print("pokes".upper())
|
判断字符串
isalpha()
判断是否为 字母 str.encode().isalpha()
str.isdigit()
判断是否为数字
str = "runoob" print(str.isalpha())
str = "runoob菜鸟教程" print(str.isalpha())
str = "this is string example....wow!!!" print(str.isalpha())
s = "中国" print s.encode( 'UTF-8' ).isalpha()
|
s = '中abCD123$%文' zm,sz,qt = 0,0,0 for i in s: if 'a' <= i <= 'z' or 'A' <= i <= 'Z': zm += 1 elif '0' <= i <= '9': sz += 1 else: qt += 1 print('字母:%d,数字:%d,其他:%d' % (zm,sz,qt))
|
s = '中abCD123$%文' zm,sz,qt = 0,0,0 for i in s: if i.encode().isalpha(): zm += 1 elif i.isdigit(): sz += 1 else: qt += 1 print(zm,sz,qt)
|
案例
class Solution: def fn(self, path: str, newpath): with open(path,'r') as f: rows = f.read().split('\n') with open(newpath, 'w') as w: w.write(rows[0]) for i in rows[1:]: cols = i.split(',') if cols[1] == 'male': cols[1] = '男' else: cols[1] = '女' cols[3] = cols[3].upper() print(cols) with open('newText.txt', 'a') as n: n.write('\n') n.write(','.join(cols))
solu = Solution() solu.fn('oldText.txt', 'newText.txt')
|
姓名,性别,年龄,午餐种类 小龙,male,25,c 小虎,male,27,a 阿红,female,25,a 阿岚,female,23,c 阿月,female,25,a
|
姓名,性别,年龄,午餐种类 小龙,男,25,C 小虎,男,27,A 阿红,女,25,A 阿岚,女,23,C 阿月,女,25,A
|
去除前后空格 strip