Python字符串操作大全

Python中字符串的定义:由Unicode码点组成的不可变序列(Strings are immutable sequences of Unicode code points)。

Python内置函数提供了强大的字符串的使用方法,熟练掌握常见的方法,对于数据处理、面试、笔试都非常有用。

dir(str)['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__','__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

首先,字符串是一种序列,所以支持切片和索引操作,具体可以看这篇文章Python基础之数据类型详解

下面是常见的内建函数用法总结:

  •  
s="hello testers !"print(s.replace('hello','hi')) #输出hi testers !

  •  
s="hello testers !"print(s.split()) #输出['hello', 'testers', '!']print(s.partition('testers')) #输出('hello ', 'testers', ' !')

  •  
s=" hellotesters! "print(s.strip()) #输出hellotesters!print(s.rstrip()) #输出 hellotesters!print(s.lstrip()) #输出hellotesters!

  •  
s1="hellotesters!"s2="HELLO TESTERS!"s3="Hello Testers!"s4=s1="hello testers!"print(s1.upper()) #输出HELLO TESTERS!print(s2.lower()) #输出hello testers!print(s3.swapcase()) #输出hELLO tESTERS!print(s1.capitalize()) #输出Hello testers!print(s4.title()) #输出Hello Testers!

  •  
s1="hello testers!"print(s1.count('l')) #输出2print(s1.find('hello')) #输出0print(s1.rfind('testers!')) #输出6

 

  • ​​​​​​​
s1="hellotesters!1234567890"s2="hellotesters"s3="1234567890"s4="HELLOTESTERS"print(s1.isalnum()) #输出Falseprint(s2.isalpha()) #输出Trueprint(s3.isdigit()) #输出Trueprint(s4.isupper()) #输出Trueprint(s2.islower()) #输出True
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

aFakeProgramer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值