Python字符串方法总结

又是一篇菜鸡笔记 在学校很多毫无意义的事情要忙没那么多时间 自己学习效率也有待提高 今天正好有时间 加上课上也讲到了这些东西 还是比较难记的 所以总结一下 没有多少时间了 加油呀

str.strip()

清除字符串两端的空格 较常用

str.capitalize()

将首字符转换成大写 如果首字符没有大写形式 就返回原字符串

1
2
3
>>> 'xhy'.capitalize()
'Xhy'
>>>

str.title()

将字符串中每个首字母 大写。判断每个单词的依据则是基于空格和标点

1
2
3
>>> 'scholar xhy'.title()
'Scholar Xhy'
>>>

str.lower()

将字符串转换为小写 仅对ascii编码的字母有效

1
2
3
>>> 'XHY'.lower()
'xhy'
>>>

str.upper()

将字符串转换为大写 会自动忽略不可转换成大写的字符

1
2
3
>>> 'scholar10'.upper()
'SCHOLAR10'
>>>

str.center()

将字符串按照给定的宽度居中显示,可以给定特殊的字符 填充多余的长度 如果指定长度小于字符串长度 则返回原字符串

1
2
>>> '12345'.center(10,"*")
'**12345***'

str.count()

统计指定字符串 在原字符串中的个数

str.count()可以指定查询字符串的起止位置

1
2
3
4
5
>>> test='Scholars work very hard'
>>> test.count('a')
2
>>> test.count('a',5,8)
1

检验邮箱格式是否正确

1
2
3
4
5
6
7
8
9
email=input("请输入email邮箱")
if email.count("@")==1:

if email.count(".")>=1:
print("格式正确")
else:
print("邮箱应包含.")
else:
print("邮箱中应包含@")

str.find() str.rfind()

从字符串左边或右边查找指定元素出现的索引位置 也可以指定 查找的起止范围 要查找的元素不存在时 返回-1

(不论左边还是右边查找得到的结果都是字符串左边数起的)

1
2
3
4
5
6
7
>>> text = 'puter protective covering'
>>> text.find('er')
3
>>> text.find('sc')
-1
>>> text.find('er',3)
3

str.index() str.rindex()

与 str.find() str.rfind()类似 不同的是如果要查找的元素不存在 则会引发ValueError

str.replice()

str.replice(old,new,count)

用新字符串代替旧字符串 可以指定替换次数

1
2
3
4
5
>>> text = 'qwe asd kkk lll qwe'
>>> text.replace('qwe','scholar')
'scholar asd kkk lll scholar'
>>> text.replace('qwe','scholar',1)
'scholar asd kkk lll qwe'

str.endswith() str.startswith()

判断字符串是否以某个指定的字符串 开头或结尾 返回布尔值 可指定查找的起止范围

1
2
3
4
5
>>> a="Scholars work very hard"
>>> a.endswith('rd')
True
>>> a.startswith("Sc")
True

str.split()

使用指定的字符将整个字符串拆分为若干个元素 并返回一个列表 ,默认没有参数时 拆分符为空格符

1
2
3
4
>>> '1,2,3'.split(',')
['1', '2', '3']
>>> 'i love python'.split()
['i', 'love', 'python']

str.isdigit()

isdigit() 方法检测字符串是否只由数字组成

1
2
3
4
5
6
>>> str = '123'
>>> str.isdigit()
True
>>> str = 'scholar'
>>> str.isdigit()
False

字符串方法的实际运用

任意读入一个字符串 判断是否为数字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
s=input("请任意输入一个数字字符串")##-1.23 1.23
if s.startswith('-'):
str1=s.split('-')##-1.23
str2=str1[1]
elif s.startswith('+'):
str1=s.split('+')
str2=str1[1]
else:
str2=s

dotCounts=str2.count('.')
if dotCounts==0 and str2.isdigit()==True:
print("%s是一个数字"%(s))
elif dotCounts==1:
strList=str2.split('.')
if strList[0].isdigit() and strList[1].isdigit():
print("%s是一个数字"%(s))
else:
print("%s不是一个数字"%(s))
else:
print("%s不是一个数字"%(s))