字符串操作3-替换/分割/大小写-Python

-替换内容:replace

  replace(old,new,count)  默认全部替换,也可以用count指定次数

-切割字符串:split,rsplit,splitlines,partition,rpartition

  split('分隔符',maxsplit)  返回结果是一个列表,maxsplit是最多分割次数

  splitlines 按行来分割

-修改大小写:capitalize,title,upper,lower

#  替换
s = '这些人都是蠢蛋,蠢蛋都不如。而那些人则是白痴,白痴都不如。'
result = s.replace('蠢蛋', '**')
print(result)  # 这些人都是**,**都不如。而那些人则是白痴,白痴都不如。
result = s.replace('蠢蛋', '**', 1)
print(result)  # 这些人都是**,蠢蛋都不如。而那些人则是白痴,白痴都不如。

#  分割
s = "张三 李四 王五"
result = s.split(' ')
print(result)  # ['张三', '李四', '王五']
result = s.split(' ', 1)
print(result)  # ['张三', '李四 王五']

#  大小写转换
s = 'hello word BIN'
print(s.title())  # Hello Word Bin 首字母大写
print(s.upper())  # HELLO WORD BIN 全部大写
print(s.lower())  # hello word bin 全部小写
print(s.capitalize())  # Hello word bin 第一个字母大写

 

posted @ 2021-09-25 10:33  逍遥abin  阅读(290)  评论(0编辑  收藏  举报