字符串相关内置函数
1.capitalize()
首字母大写方法,()里面不需要填写任何参数
a = 'hello python'
print(a.capitalize())
然后运行代码后输出:
Hello python
可以看到已经把字符串的首字母转换成了大写
2.lower()
将大写字符转换成小写方法,()里面不需要填写任何参数
b = 'HELLO PYTHON'
print(b.lower())
然后运行代码后输出:
hello python
可以看到已经把大写的字符串换成了小写
3.upper()
将小写字符串转换成大写的方法,()里面不需要填写任何参数
c = 'hello python'
print(c.upper())
然后运行代码后输出:
HELLO PYTHON
4.swapcase()
把字符串内小写字母的转换成大写,大写字母转换成小写
d = 'heLLO PythoN'
print(d.swapcase())
然后运行代码后输出:
HEllo pYTHOn
5.zfill()
为字符串定义长度,如不满足,缺少的部分用0补齐
e = 'abc'
print(e.zfill(10))
然后运行代码后输出:
0000000abc
注意:
1:与字符串的字符无关
2:如果定义长度小于当前字符串长度,则不发生变化
6.count()
返回当前字符串内元素的个数
例如:a = hello world,我们想查找这里面o的个数
f = ' one two dd ff sews'
print(f.count('o'))
然后运行代码后输出:
2
注意:如果查询元素不存在,则返回0
7.startswith() 和 endswith()
startswith():判断字符串【开始位】是否是某个元素
endswith():判断字符串【结尾位是】否是某个元素
g = 'hello python'
print(g.startswith('h'))
print(g.endswith('n'))
然后运行代码后输出:
True
True
8.find() 和index()
find(): 你想查询的元素,返回一个整形
index():你想查询的元素,返回一个整形或报错
h = 'hello python'
print(h.find('y'))
print(h.index('o'))
然后运行代码后输出:
7
4
find()和index()的区别
如果find找不到元素,则返回-1
如果index找不到元素,会导致程序报错
9.strip,lstrip,rstrip
strip():传入想去掉的元素,也可以不写(则是空格),将去掉左右两边的指定元素,默认是空格
i = ' des ddd ccc bas '
print(i.strip(' '))
print(i.lstrip(' '))
print(i.rsplit(' '))
然后运行代码后输出:
des ddd ccc bas
des ddd ccc bas
['', '', '', 'des', 'ddd', 'ccc', 'bas', '', '', '']
lstrip():则是去掉左边(开头元素或空格)
strip():则是去掉右边(结尾元素或空格)
10.replace()
将字符串内旧的元素替换成新的元素,并且可以指定数量
a = a.rep;ace(old,new,max)
j = 'hello python'
print(j.replace('h', 'H', 1)) # 将第一个 h 替换为 H,max参数传空默认替换所有
然后运行代码后输出:
Hello python
11.字符串bool集合
isspace():判断字符串是否是一个由空格组成的字符串,返回布尔类型
istitle(): 判断字符串是否是一个标题类型,返回布尔类型
isupper():判断字符串中字符是否都是大写,返回布尔类型
islower():判断字符串中字符是否都是小写,返回布尔类型
本节所有代码
# 字符串内置函数
# 1.capitalize() --- 首字母大写方法
a = 'hello python'
print(a.capitalize())
# lower() 将大写字符转换成小写
b = 'HELLO PYTHON'
print(b.lower())
# upper() ---- 将小写字符串转换成大写的方法,()里面不需要填写任何参数
c = 'hello python'
print(c.upper())
# swapcase() ----把字符串内小写字母的转换成大写,大写字母转换成小写
d = 'heLLO PythoN'
print(d.swapcase())
# zfill() --- 为字符串定义长度,如不满足,缺少的部分用0补齐
e = 'abc'
print(e.zfill(10))
# count() --- 返回当前字符串内元素的个数
f = ' one two dd ff sews'
print(f.count('o'))
# startswith() 和 endswith() --- 判断字符串首字母和尾字母
g = 'hello python'
print(g.startswith('h'))
print(g.endswith('n'))
# find() 和index()
# 用法:
# a.find(item): item→你想查询的元素,返回一个整形
# a.index(item):item→你想查询的元素,返回一个整形或报错
h = 'hello python'
print(h.find('y'))
print(h.index('o'))
# strip,lstrip,rstrip ---过滤字符串
i = ' des ddd ccc bas '
print(i.strip(' '))
print(i.lstrip(' '))
print(i.rsplit(' '))
# replace() 将字符串内旧的元素替换成新的元素,并且可以指定数量
j = 'hello python'
print(j.replace('h', 'H', 1)) # 将第一个 h 替换为 H
输出:
F:\xiaol_test\Scripts\python.exe G:/pythonProject/xiaol_test/字符串内置函数.py
Hello python
hello python
HELLO PYTHON
HEllo pYTHOn
0000000abc
2
True
True
7
4
des ddd ccc bas
des ddd ccc bas
['', '', '', 'des', 'ddd', 'ccc', 'bas', '', '', '']
Hello python
Process finished with exit code 0