Skip to content

数据类型的操作与方法 - str字符串

在py中通过操作数据类型本身自带的一些方法,可以将原有的数据经过操作返回新的数据

听不懂啊

大小写转换

  • upper() 将小写转换成大写
  • lower() 将大写转换成小写
  • title() 将每个单词的第一个字符转成大写 其余转成小写
  • capitalize() 将第一个字符转成大写 其余转成小写
  • swapcase() 将字符串中的大写转小写 小写转大写
python
a = 'ab'
b = 'AB'
c = 'bAAAAAAAAA'
b = 'HELLO world'
print(a.upper()) # 将小写转换成大写
print(b.lower()) # 将大写转换成小写
print(c.capitalize()) # 将第一个字符转换成大写 其余转换成小写
print(b.title()) # 将每个单词的第一个字符转换成大写 其余转换成小写
print(b.swapcase()) #将字符串中的大写转成小写  小写转成大写

PS D:\学习干货\后端\Python\基础学习> py dataTypeFunction.py
AB
hello world
Baaaaaaaaa
Hello World
hello WORLD

查找与替换

查找
  • find(sub,start,end) 查找字符串中是否包含某个字串 如果包含返回这个子串的索引位置 如果不包含返回 -1, 可以指定查找的范围 start end(可选)
  • rfind(sub,start,end) 从右往左查找字符串中是否包含某个字串 如果包含返回这个子串的索引位置 如果不包含返回 -1, 可以指定查找的范围 start end(可选)
  • index(sub,start,index) 查找字符串中是否包含某个字串 如果包含返回这个子串的索引位置 如果不包含抛出 ValuerError 异常 可以指定查找的范围 start end(可选)
  • rindex(sub,start,end) 从右往左查找字符串中是否包含某个字串 如果包含返回这个子串的索引位置 如果不包含抛出 ValuerError 异常 可以指定查找的范围 start end(可选)
替换
  • replace(old,new,num) 查找字符串中 old 子串 替换成 new 子串 可指定替换次数 (可选) 默认为全部替换
python
e = '前端猛男是个大帅哥'

print('find',e.find('猛男')) # 2
print('find',e.find('帅哥',0,5)) # -1

print('rfind',e.rfind('帅哥')) # 7
print('rfind',e.rfind('帅哥',0,5)) # -1
try:
    print('index',e.index('帅哥')) # 7
    print('index',e.index('某某某',0,5)) # 抛错 ValueError

    print('rindex',e.rindex('帅哥')) # 7
    print('rindex',e.rindex('某某某',0,5)) # 抛错 ValueError
except ValueError as errorAlias:
    print('index或rindex未找到进程报错:',errorAlias) # 打印报错原因

print('replace',e.replace('帅哥','学霸')) # 前端猛男是个大学霸
print('replace',e.replace('学霸','帅哥',1)) # 前端猛男是个大帅哥


PS D:\学习干货\后端\Python\基础学习> py dataTypeFunction.py
find 2
find -1
rfind 7
rfind -1
index 7
index或rindex未找到进程报错: substring not found
replace 前端猛男是个大学霸
replace 前端猛男是个大帅哥

分割与拼接

分割
  • split(separator,maxlength) 以指定内容为分隔符分割字符串并返回一个分割后的list列表 默认以空格为分隔符 可限制最大分割次数 (可选)
  • rsplit(separator,maxlength) 从右往左以指定内容为分隔符分割字符串并返回一个分割后的list列表 默认以空格为分隔符 可限制最大分割次数 (可选)
  • splitlines(bool) 以换行符为分隔符分割字符串并返回一个分割后的list列表 接收一个Bool值 True 保留换行符 False 不保留换行符 默认False
  • partition(separator) 以指定内容为分隔符分割字符串并返回一个分割后的tuple元组 分割后的元组包含三个元素 第一个元素为分隔符前面的字符串 第二个元素为分隔符 第三个元素为分隔符后面的字符串 若无找到指定分隔符则返回(原字符串,'', '')
  • rpartition(separator) 从右往左以指定内容为分隔符分割字符串并返回一个分割后的tuple元组 分割后的元组包含三个元素 第一个元素为分隔符前面的字符串 第二个元素为分隔符 第三个元素为分隔符后面的字符串 若无找到指定分隔符则返回('', '', 原字符串)
拼接
  • join(iterable) # 以指定内容字符串为分隔符 将可迭代的对象中元素合并成一个字符串
  • + 可以使用 + 运算符将两个字符串拼接在一起
python
f = '前端猛男 是个 大帅哥'
print('split',f.split()) # ['前端猛男', '是个', '大帅哥']
print('split',f.split(' ',1)) # ['前端猛男', '是个 大帅哥']

print('rsplit',f.rsplit()) # ['前端猛男', '是个', '大帅哥']
print('rsplit',f.rsplit(' ',1)) # ['前端猛男 是个', '大帅哥']

h = 'hello\nworld'
print('splitlines',h.splitlines()) # ['hello', 'world']
print('splitlines',h.splitlines(True)) # ['hello\n', 'world']

print('partition','前端-猛男-18岁'.partition('-')) # partition ('前端', '-', '猛男-18岁')
print('parttition','前端-猛男-18岁'.partition('666')) # parttition ('前端-猛男-18岁', '', '')
print('rpartition','前端-猛男-18岁'.rpartition('-')) # rpartition ('前端-猛男', '-', '18岁')
print('rpartition','前端-猛男-18岁'.rpartition('666')) # rpartition ('', '', '前端-猛男-18岁')

strList = ['a','b','c','d']
distData = {'a':1,'b':2,'c':3,'d':4}
setData = {'a','b','c','d'}
tubleData = ('a','b','c','d')
print('join','-'.join(strList)) # a-b-c-d
print('join','-'.join(distData)) # a-b-c-d
print('join','-'.join(setData)) # c-d-a-b 随机的
print('join','-'.join(tubleData)) # a-b-c-d
print('+','前端'+ '猛男') # abcd

PS D:\学习干货\后端\Python\基础学习> py dataTypeFunction.py
split ['前端猛男', '是个', '大帅哥']
split ['前端猛男', '是个 大帅哥']
rsplit ['前端猛男', '是个', '大帅哥']
rsplit ['前端猛男 是个', '大帅哥']
splitlines ['hello', 'world']
splitlines ['hello\n', 'world']
partition ('前端', '-', '猛男-18岁')
parttition ('前端-猛男-18岁', '', '')
rpartition ('前端-猛男', '-', '18岁')
rpartition ('', '', '前端-猛男-18岁')
join a-b-c-d
join a-b-c-d
join c-d-a-b
join a-b-c-d
+ 前端猛男

去除空白字符

  • strip(chars) 去除字符串首尾两边的指定字符 如果未指定默认为空格
  • lstrip(chars) 去除字符串开头的指定字符 如果未指定默认为空格
  • rstrip(chars) 去除字符串右边的指定字符 如果未指定默认为空格
python
charstr = ' 你好猛男 '
charstr2 = '---你好猛男---'
print('strip',charstr.strip()) # 你好猛男
print('strip',charstr2.strip('-')) # 你好猛男

print('lstrip',charstr2.lstrip()) #  你好猛男---
print('rstrip',charstr2.rstrip()) #  ---你好猛男

判断方法

  • startswith(str,start,end) 判断字符串是否以指定内容开头 返回 True False 可指定查找范围 start end(可选)
  • endswith(str,start,end) 判断字符串是否以指定内容结尾 返回 True False 可指定查找范围 start end(可选)
  • isalnum() 判断字符串是否由字母和数字组成 返回 True False
  • isalpha() 判断字符串是否由字母组成 返回 True False
  • isdigit() 判断字符串是否由数字组成 返回 True False
  • isspace() 判断字符串是否由空格组成 返回 True False
  • islower() 判断字符串是否由小写字母组成 返回 True False
  • isupper() 判断字符串是否由大写字母组成 返回 True False
  • istitle() 判断字符串是否由标题化的字符串组成 返回 True False
  • == 使用 == 运算符判断字符串是否相等 返回 True False
python
strswith = '你好猛男'
print('startswith',strswith.startswith('你好')) # True
print('startswith',strswith.startswith('你好',0,2)) # True
print('startswith',strswith.startswith('猛男')) # False

print('endswith',strswith.endswith('猛男')) # True
print('endswith',strswith.endswith('猛男',2,4)) # True
print('endswith',strswith.endswith('你好')) # False

print('isalpha','ABC'.isalpha()) # True
print('isdigit','123'.isdigit()) # True
print('isalnum','123abc'.isalnum()) # True
print('isspace','  '.isspace()) # True
print('islower','abc'.islower()) # True
print('isupper','ABC'.isupper()) # True
print('istitle','Abc'.istitle()) # True
print('==','abc' == 'abc') # True

PS D:\学习干货\后端\Python\基础学习> py strFunction.py
startswith True
startswith True
startswith False
endswith True
endswith True
endswith False
isalpha True
isdigit True
isalnum True
isspace True
islower True
isupper True
istitle True
== True

格式化方法

  • format(...arguments) 格式化字符串,通过 {} 来占位插入值
  • f-string Python 3.6 及以上版本支持的一种字符串格式化方法,使用 f 前缀,在字符串中直接使用 {} 插入变量
  • format_map(dist) 格式化字符串,通过dist对象的{key}来插入
python
name = '猛男'
age = 18
s = '我叫{} 我今年刚满{}岁'.format(name,age) # format()格式化字符串

fs= f'我叫{name} 我今年刚满{age}岁' # f-string格式化字符串

s_map = {'name':'猛男'  ,'age':18} # format_map()格式化字符串
s_map_str = '我叫{name} 我今年刚满{age}岁'

print(s)
print(fs)
print('format_map',s_map_str.format_map(s_map)) # format_map()格式化字符串

PS D:\学习干货\后端\Python\基础学习> py strFunction.py
我叫猛男 我今年刚满18岁
我叫猛男 我今年刚满18岁
format_map 我叫猛男 我今年刚满18岁

计数方法

  • count(sub,start,end) 统计字符串中指定子串出现的次数 返回一个整数 可指定查找范围 start end(可选)
  • len(str) 统计字符串的长度 返回一个整数
python
print('count','abcabacsa'.count('a')) 
print('conut','abcabacsa'.count('a',0,5)) 
print('len',len('123456789'))


PS D:\学习干货\后端\Python\基础学习> py strFunction.py
count 4
conut 2
len 9

对齐与填充

  • center(width,fillchar) 居中对齐 接收两个参数 width 字符串的总宽度 fillchar 填充字符 默认空格 返回一个新的字符串
  • ljust(width,fillchar) 左对齐 接收两个参数 width 字符串的总宽度 fillchar 填充字符 默认空格 返回一个新的字符串
  • rjust(width,fillchar) 右对齐 接收两个参数 width 字符串的总宽度fillchar 填充字符 默认空格 返回一个新的字符串
  • zfill(width) 右对齐 接收一个参数 width 字符串的总宽度 以0填充补齐宽度 返回一个新的字符串
python
print('hello'.ljust(10,'*')) 
print('hello'.rjust(10,'*')) 
print('hello'.center(10,'*')) 
print('777'.zfill(10))

PS D:\学习干货\后端\Python\基础学习> py strFunction.py
hello*****
*****hello
**hello***
0000000777

编码与解码

  • encode(encoding,errors) 编码 接收两个参数 encoding 编码格式 默认格式utf-8 , errors 错误处理方式 默认 strict 常见值有 strict(遇到错误抛出异常)、ignore(忽略错误)、replace(用 ? 替换错误字符)等 返回一个新的字符串
  • decode(encoding,errors) 解码 接收两个参数 encoding 编码格式 默认格式utf-8 , errors 错误处理方式 默认 strict 常见值有 strict(遇到错误抛出异常)、ignore(忽略错误)、replace(用 ? 替换错误字符)等 返回一个新的字符串
python
strencode = '你好'.encode('utf-8','strict') 
strdecode = strencode.decode('utf-8','strict')
print('encode',strencode)
print('decode',strdecode)

PS D:\学习干货\后端\Python\基础学习> py strFunction.py
encode b'\xe4\xbd\xa0\xe5\xa5\xbd'
decode 你好

切片与索引

  • 索引 获取字符串中指定索引位置的字符 从0开始 也可以负数索引从字符串末尾开始
  • 切片 获取字符串中指定区间的字符 start🔚step 的形式 从start开始 到end结束(不包含) 步长为step 默认为1 返回一个新的字符串
python
print("索引",'123456'[0]) 
print('索引','123456'[-1])

print('切片','123456'[0:3])
print('切片','123456'[0:3:2]) 
print('切片','1234567890'[::2]) 

PS D:\学习干货\后端\Python\基础学习> py strFunction.py
索引 1
索引 6
切片 123
切片 13
切片 13579

看到这里头发已经思考掉两根啦吧~ 头发稀疏

好好加油吧,少年!