python_字符串

1、字符串去除空格及换行符

import  pprint
s="  skffkdj  "
pprint.pprint(s.strip()) #去除左右空格及换行
pprint.pprint(s.lstrip()) #去除左空格及换行
pprint.pprint(s.rstrip()) #去除右空格及换行


D:studypython	estvenvScriptspython.exe D:/study/python/test/dd.py
'skffkdj'
'skffkdj  '
'  skffkdj'

2、字符串替换操作

s="abc de fg"
print(s.replace('a','A')) #替换用后面的值替换前面的值
print(s.replace(' ',''))  #替换空格


D:studypython	estvenvScriptspython.exe D:/study/python/test/dd.py
Abc de fg
abcdefg

3、字符串索引

s="abcdefgaa"
print(s.index('c')) #返回字符串的索引
print(s.count('a')) #统计字符串出现次数
print(s.find('a'))  #返回字符串的索引,当多个返回第一个,当字符不在字符串,返回-1
print(s.find('y')) #字符不存在,返回-1


D:studypython	estvenvScriptspython.exe D:/study/python/test/dd.py
2
3
0
-1

4、字符以什么开头或结尾,常见例子:不知道字符的全部,仅知道开始或结尾来查询该字符串

startswith和endswith返回为True和False
s="abcdefgaa"
print(s.startswith('a')) #字符串是否以a开头
print(s.endswith('a')) #字符串是否以a结尾


D:studypython	estvenvScriptspython.exe D:/study/python/test/dd.py
True
True

5、字符串大小写转换

s="abcdefgaa"
s2="ASDWWE"
print(s2.lower()) #字符串转小写
print(s.upper()) #字符串转大写
print(s.capitalize()) #字符串转首字母大写


D:studypython	estvenvScriptspython.exe D:/study/python/test/dd.py
asdwwe
ABCDEFGAA
Abcdefgaa

6、字符串是不是整数

s="abcdefgaa"
s2="1234"
print(s.isdigit())
print(s2.isdigit())


D:studypython	estvenvScriptspython.exe D:/study/python/test/dd.py
False
True

7、字符串居中左右加分界线

s="abcdefgaa"
print(s.center(20,"=")) #字符串+等号整体长度,=表示左右加的符号


D:studypython	estvenvScriptspython.exe D:/study/python/test/dd.py
=====abcdefgaa======

8、字符串补0操作

s="1"
print(s.zfill(3)) #字符串填充,3位数,不足的补0


D:studypython	estvenvScriptspython.exe D:/study/python/test/dd.py
001

9、判断字符

s="DFD"
print(s.isupper())  #是不是大写字母
print(s.islower())   #是不是小写字母
print(s.isalpha())  #是字母和汉字才会返回true,其他的都返回false
print(s.isalnum()) #是数字,字母和汉字才会返回true,其他的都返回false
print(s.isspace())  #是否是空格


D:studypython	estvenvScriptspython.exe D:/study/python/test/dd.py
True
False
True
True
False

10、字符串占位通过format和format_map传参

s="{name},{passwd}" #字符串存在大括号标识
s2=s.format(passwd="12345",name="zhaozhao") #通过赋值就行传参
s3=s.format_map({"name":"zhaozhao2","passwd":"123456"}) #通过字典的方式进行传参
print(s2)
print(s3)

D:studypython	estvenvScriptspython.exe D:/study/python/test/dd.py
zhaozhao,12345
zhaozhao2,123456

11、字符串分割

字符串分割默认是空格分割,如果是其他符合分割需要给予传参,另外分割后的字符串是个list集合

stus='xiaoming,xiaohei,xiaobai,jaojun'
print(stus.split(','))     #分割字符串,默认是空格,如果指定了以指定的分隔符进行分割



D:studypython	estvenvScriptspython.exe D:/study/python/test/dd.py
['xiaoming', 'xiaohei', 'xiaobai', 'jaojun']

12、字符串串联

list可通过join把每个字符串连接起来,作为一个整体的字符串进行输出

li=['xiaoming', 'xiaohei', 'xiaobai', 'jaojun']
print(','.join(li))    #把list里面的每个元素通过指定的字符串连接起来

D:studypython	estvenvScriptspython.exe D:/study/python/test/dd.py
xiaoming,xiaohei,xiaobai,jaojun
原文地址:https://www.cnblogs.com/xiaokuangnvhai/p/10943722.html