python学习笔记(四)字符串及字符串操作

字符串

  字符串可以存任意类型的字符串,比如名字,一句话等等。

字符串还有很多内置方法,对字符串进行操作,常用的方法如下:

复制代码
 1 name1='hello world'
 2 print(name.capitalize())#首写字母大写
 3 print(name1.capitalize())#首写字母大写Hello world
 4 print(name1.center(50,'-'))#50个-,把name1放中间-------------------hello world--------------------
 5 print(name.endswith('u'))#是否以x结尾 False
 6 print(name1.endswith('d'))#是否以x结尾 True
 7 print(name.expandtabs(30))#补入\t的次数my                             name is {name},age is{age}.
 8 print(name1.find('n'))#查找字符串的索引5(\t代表3个字符)
 9 print(name.format(name='niuniu',age=18))#这个是格式字符串my      name is niuniu,age is18.
10 print(name.format_map({'name':'niuniu','age':19}))#这个也是格式化字符串,后面跟的是一个字典,字典在后面也会写
11 #my      name is niuniu,age is19.
12 print('abA123'.isalnum())#是否包含数字和字母 True
13 print('abA'.isalpha())#是否有英文字母True
复制代码
复制代码
 1 name = 'My \t name is {name},age is{age}.'
 2 print('122'.isdigit())#是否有数字True
 3 print('aa'.isidentifier())#是否是一个合法的变量名True
 4 print('aa'.islower())#是否是小写字母True
 5 print('AA'.isupper())#是否是大写字母True
 6 print('Loadrunner Book'.istitle())#是不是一个标题,判断首字母是否大写True
 7 print('+'.join(['hehe','haha','ee']))#拼接字符串 hehe+haha+ee
 8 print(name.lower())#变成小写my      name is {name},age is{age}.
 9 print(name.upper())#变成大写MY      NAME IS {NAME},AGE IS{AGE}.
10 print('\nmysql \n'.lstrip())#默认去掉左边的空格和换行
11 print('\nmysql \n'.rstrip())#默认去掉右边的空格和换行
12 print('\nmysql \n'.strip())#默认去掉两边的空格和换行
13 p=str.maketrans('abcdefg','1234567')#前面的字符串和后面的字符串做映射
14 print('cc ae gg'.translate(p))#输出按照上面maketrans做映射后的字符串33 15 77
复制代码
复制代码
1 new_p=str.maketrans('1234567','abcdefg')
2 print('cc ae gg'.translate(new_p))
3 print('mysql is db.'.replace('mysql','oracle',1))#替换字符串oracle is db.
4 print('mysql is db.mysql is db.mysql is db.'.replace('mysql','oracle',2))#替换字符串oracle is db.oracle is db.mysql is db.
5 print('mysql is is db'.rfind('is'))#返回最右边字符的下标 9
6 print('1+2+3+4'.split('+'))#切割字符串,返回一个list ['1', '2', '3', '4']
7 print('1+2+3\n1+2+3+4'.splitlines())#按照换行符分割['1+2+3', '1+2+3+4']
8 print('Abcdef'.swapcase())#大小写反转aBCDEF
复制代码
0
0


currentDiggType = 0;

« 上一篇: python学习笔记(三)字典操作和元组操作
» 下一篇: python学习笔记(五)文件操作和集合
    </div>

猜你喜欢

转载自blog.csdn.net/ccbulougen/article/details/81189461