前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python字符串操作大全

Python字符串操作大全

作者头像
吾非同
发布2020-10-26 11:29:06
3390
发布2020-10-26 11:29:06
举报
文章被收录于专栏:吾非同吾非同

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

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

代码语言:javascript
复制
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', 'cent
er', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isuppe
r', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfi
ll']

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

下面是常见的内建函数用法总结:
代码语言:javascript
复制
s="hello testers !"
print(s.replace('hello','hi')) #输出hi testers !
代码语言:javascript
复制
s="hello testers !"
print(s.split()) #输出['hello', 'testers', '!']
print(s.partition('testers')) #输出('hello ', 'testers', ' !')
代码语言:javascript
复制
s=" hellotesters! "
print(s.strip()) #输出hellotesters!
print(s.rstrip()) #输出 hellotesters!
print(s.lstrip()) #输出hellotesters!
代码语言:javascript
复制
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!
代码语言:javascript
复制
s1="hello testers!"
print(s1.count('l')) #输出2
print(s1.find('hello')) #输出0
print(s1.rfind('testers!')) #输出6
代码语言:javascript
复制
s1="hellotesters!1234567890"
s2="hellotesters"
s3="1234567890"
s4="HELLOTESTERS"
print(s1.isalnum()) #输出False
print(s2.isalpha()) #输出True
print(s3.isdigit()) #输出True
print(s4.isupper()) #输出True
print(s2.islower()) #输出True
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-03-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 吾非同 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ?
  • Python中字符串的定义:由Unicode码点组成的不可变序列(Strings are immutable sequences of Unicode code points)。
    • 下面是常见的内建函数用法总结:
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档