sla orm 自动 false sdf ide 字符串长度 规则
字符串特性是不可修改
- 1name ='lao cui'
- 2 print(name.capitalize())# 将字符串的首字母大写
- 3 print(name.upper())#小写-->大写
- 4 print('cUI Qhaha'.lower())#大写-->小写
- 5 print(name.title())#标题的形式,字符串中每个空格后面的首字母都大写
- 6 print('cUI Qhaha'.isupper())#字符串是不是全是大写
- 7 print('cui qhaha '.islower())#字符串是不是全是x小写
- 8 print('cUI Qhaha'.swapcase())#大写-->小写,小写-->大写
- 9 print('Lao Cui Ha'.istitle())#是不是标题的格式
输出:
- 1----2 Lao cui
- 3 LAO CUI
- 4 cui qhaha
- 5 Lao Cui
- 6 False
- 7 True
- 8 Cui qHAHA
- 9True
>>> test1'lu si zhen zhu'>>> test1.count('z') #查找字符串中有几个 z2
- 1 print('Lao cui a'.center(30,'*'))#将字符串长度更改为30,不够的用*替代,原字符串放在中间
- 2 print('Lao cui a'.ljust(30,'*'))#同上,放左边
- 3 print('Lao cui a'.rjust(30,'*'))#同上
- 4 print('Lao cui a'.zfill(30))#用0补全
输出:
- 1**********Lao cui a***********2Lao cui a*********************3*********************Lao cui a
- 4000000000000000000000Lao cui a
>>> '哈哈'.encode()b'\xe5\x93\x88\xe5\x93\x88'
python3 里默认的是 utf-8
相当于
>>> '哈哈'.encode('utf-8')b'\xe5\x93\x88\xe5\x93\x88'
>>> [email protected]([email protected])True>>>
常用的方法:比如判断是否为有效的邮箱地址等
>>> [email protected]('63.c')6>>>
'63.c'的第一个字符是 6,下标是 6
>>> 'abc def abc'.find('abc')0>>> 'abc def abc'.rfind('abc')8>>>
>>> [email protected]('6')6>>> [email protected]('c')9
>>> 'woaini'[2:-1:2]'an'>>>
>>> 'my name is {name},I am {year}.'.format(name ='laocui',year = 27)'my name is laocui,I am 27.'>>>
>>> 'my name is {name},I am {year}.'.format_map({'name':'laocui','year':27})'my name is laocui,I am 27.'
- 1print('123Abc'.isalnum()) # 判断字符串是否只包含英文字符和数字
- 2print('123abc'.isalpha()) #是否只包含英文字母
- 3print('AbcDc'.isalpha()) #是否只包含英文字母
- 4print('12.34'.isdigit()) #是否为一个整数
- 5print('12345'.isdigit()) #是否为一个整数
- 6print('1abcD'.isupper()) #是否都是大写
- 7print('1abcd'.islower()) #是否都是小写
输出:
- 1 True
- 2 False
- 3 True
- 4 False
- 5 True
- 6 False
- 7True
另外还有很多方法,不常用就不写了
- >>> b="ddefdsdff_哈哈"
- >>> b.isidentifier() #检测一段字符串可否被当作标志符,即是否符合变量命名规则
- True
- print('+'.join(['1','2','3'])) #python3中,join里面列表中的数字都要写成字符串形式输出:1+2+3 ,我用type输出值,返回
print('笨蛋'.join(['你是',', 他是','。'])) 输出:你是笨蛋, 他是笨蛋。,type,返回 <class'str'>
- p = str.maketrans('abcdef','123456') #'abcdef'与'123456'一一对应print('lao cui'.translate(p)) #替换
- print('lao cui haha'.replace('a','A'))#将字符串中的小a全部替换为A,默认全替换,后面数字表示从左到右替换几个
- print('lao cui haha'.replace('a','A',2))
输出:
- lAo cui hAhA
- lAo cui hAha
- 1 print('wo hen ai ni'.split())#默认以空格为分隔符
- 2 print('wo hen ai ni'.split('n'))#指定以'n'为分隔符
- 3 print('wo hen\n ai\n ni'.splitlines())#以换行符为分隔符
输出:
- 1['wo','hen','ai','ni']
- 2['wo he',' ai ','i']
- 3['wo hen',' ai',' ni']
python 学习 - 基础 - day3 - 字符串操作
来源: http://www.bubuko.com/infodetail-2047249.html