Python字符串常用操作

一、字符串的切片

1.1、通过下标及下标范围取值

my_str = 'myNameIsTaichi'
value1 = my_str[2] # 正向 N
value2 = my_str[-5] # 反向 从 -1 开始 a

字符串分割,语法:string[end: step]

  • start:头下标,以0开始
  • end:尾下表,以-1开始
  • step 步长
str = "abc-123-如果我是DJ你会爱我吗.mp4"
print(str[0:7]) #默认步长是1,可以不写
# 结果:abc-123

print(str[0:-9]) #负数是从右往左截取
# 结果:abc-123-如果我是DJ

print(str[8:]) #不写右边就是一直到结尾
# 结果:如果我是DJ你会爱我吗.mp4

1.2、index方法:查找特定字符串的下标索引值

my_str = "%pokes$@163&.com*"
value3 = my_str.index("pokes")
print(value3) #1

#运行结果是“1”

注意:1是”pokes”起始下标,即p所在的下标位置

1.3、replace方法:字符串替换

语法:string.replace(“被替换的内容”,“替换后的内容”[,次数])

str2= "ithahahaaa and ithehehehe"
new_str2 = str2.replace("it","pokes") #将it替换成pokes
print(new_str2)

#运行结果:pokeshahahaaa and pokeshehehehe

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) # 0.01

1.6、count方法,统计字符串中某字符出现的次数

str6= "heihei hehe haha"
cishu = str6.count("he")
print(cishu)

#运行结果:4

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

1.9、join() 列表转字符串

二、字符串判断

2.1、判断字符串是否出现过

查询字母k是否出现,如果出现结果返回索引,没出现则返回-1

print("pokes".find("k"))  # 2
print("pooes".find("k")) # -1

print("k" in "pooes") # False
print("k" in "pokes") # True

2.2 、判断是否以xxx开头

判断是否以xxx开头,返回布尔值

# 判断是否以k开头,返回布尔值
print("pokes".startswith("k")) # False
print("kpokes".startswith("k")) # True

2.3、判断是否以xxx结尾

# 判断是否以k结尾,返回布尔值
print("pokes".endswith("k")) # False
print("kpokesk".endswith("k")) # True

2.4、判断字符串是否只包含数字

str_1 = "123"
str_2 = "Abc"
str_3 = "123Abc"

print(str_1.isdigit()) # True
print(str_2.isdigit()) # False
print(str_3.isdigit()) # False

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):
# 如果item不包含列表中的任何一个字符串,‌则执行这里的代码
print("过滤条件满足")

2.7字符串字母大小写转换和判断

  • capitalize,将字符串得第一个字符转换成大写
  • title,每个单词得首字母大写
  • istitle, 判断每个单词得首字母是否大写
  • upper 全部转换成大写
  • lower 全部转换成小写
message = 'zhaorui is a beautiful girl!'

# capitalize

msg = message.capitalize() #将字符串得第一个字符转换成大写
print(msg)

# title
msg = message.title() #每个单词得首字母大写
print(msg)


# istitle
cmd = msg.istitle() #判断每个单词得首字母是否大写
print(cmd)

spokes = message.istitle() #判断每个单词得首字母是否大写
print(spokes)

# upper 全部转换成大写

msg = message.upper()
print(msg)

# lower 全部转换成小写
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()) #pokes,转换成小写
print("pokes".upper()) #POKES,转换成小写

判断字符串

  • isalpha() 判断是否为 字母 str.encode().isalpha()
  • str.isdigit() 判断是否为数字
str = "runoob"
print(str.isalpha()) # True

str = "runoob菜鸟教程"
print(str.isalpha()) # False

str = "this is string example....wow!!!"
print(str.isalpha()) # False

s = "中国"
print s.encode( 'UTF-8' ).isalpha() # False


# 统计字符串中字母、数字、其他字符的数量
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)

案例

  • 性别:
    • male => 男
    • female => 女
  • 午餐种类改为大写
#coding=utf-8

class Solution:
def fn(self, path: str, newpath):
with open(path,'r') as f: # r 读取
rows = f.read().split('\n')
with open(newpath, 'w') as w: # 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: # a 不覆盖
n.write('\n')
n.write(','.join(cols))


solu = Solution()
solu.fn('oldText.txt', 'newText.txt')
  • oldText
姓名,性别,年龄,午餐种类
小龙,male,25,c
小虎,male,27,a
阿红,female,25,a
阿岚,female,23,c
阿月,female,25,a
  • newText
姓名,性别,年龄,午餐种类
小龙,男,25,C
小虎,男,27,A
阿红,女,25,A
阿岚,女,23,C
阿月,女,25,A

去除前后空格 strip