字符串常用方法汇总
字符串有很多常用的方法,我们需要熟悉。我们通过表格将这些方法汇总起来,方便大家查
阅。希望大家针对每个方法都做一次测试。
常用查找方法
我们以一段文本作为测试:
a='''我是攻城狮,今年 20 岁了,我在腾讯上班。'''
>>> len(a)
22
>>> a.startwith('我是')
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
a.startwith('我是')
AttributeError: 'str' object has no attribute 'startwith'
>>> a.startswith('我是')
True
>>> a.endswith('上班')
False
>>> a.find('岁')
12
>>> a.rfind('我')
15
>>> a.count('我')
2
>>> a.isalnum()
False
>>>
去除首尾信息
我们可以通过 strip()去除字符串首尾指定信息。通过 lstrip()去除字符串左边指定信息,
rstrip()去除字符串右边指定信息。
【操作】去除字符串首尾信息
>>> "@@@gcs@#@@".strip("@")
'gcs@#'
>>> "@@@gcs@#@@".lstrip("@")
'gcs@#@@'
>>> "@@@gcs@#@@".rstrip("@")
'@@@gcs@#'
>>> "@@@gcs@#@@".strip()
'@@@gcs@#@@'
>>> " gcs ".strip()
'gcs'
>>>
大小写转换
编程中关于字符串大小写转换的情况,经常遇到。我们将相关方法汇总到这里。为了方便学
习,先设定一个测试变量:
a = "gcs ke yi cheng wei zui hao de cheng xu yuan"

方法
格式排版
center()、ljust()、rjust()这三个函数用于对字符串实现排版。示例如下:
>>> a = "gcs"
>>> a.center(10,"#")
'###gcs####'
>>> a.center(10)
' gcs '
>>> a.ljust(10,"#")
'gcs#######'
>>>
其他方法
- isalnum() 是否为字母或数字
- isalpha() 检测字符串是否只由字母组成(含汉字)。
- isdigit() 检测字符串是否只由数字组成。
- isspace() 检测是否为空白符
- isupper() 是否为大写字母
- islower() 是否为小写字母
自行演示!!!