目录
六、字符串字母全变大写或小写 (upper())或(lower())
一、字符串的切割 (split())
split函数的语法:str.split(sep,num)
str是一个字符串,sep是分隔符,num是分割次数
# 不设置参数
s = '1 2 3 4 5 6 7 8 9'
print(s.split())
# 结果:['1', '2', '3', '4', '5', '6', '7', '8', '9']
# 设置分隔符
s = '1|2|3|4|5|6|7|8|9'
print(s.split('|'))
# 结果:['1', '2', '3', '4', '5', '6', '7', '8', '9']
# 设置分隔符和分割次数
s = '1|2|3|4|5|6|7|8|9'
print(s.split('|', 5))
# 结果:['1', '2', '3', '4', '5', '6|7|8|9']
二、统计字符串长度 (len())
len(字符串)
s = '人生苦短,我学Python!'
print(len(s))
# 结果:14
三、字符串的替换 (replace())
replace函数的语法:str.replace(替换前文本,替换后文本)
s = '人生苦短,我学Python!'
print(s.replace('Python', 'C'))
# 结果:人生苦短,我学C!
四、判断是否为字符串字串 (in)
s1 = '人生苦短,我学Python!'
s2 = '人生苦短'
print(s2 in s1)
# 结果:True
五、字符串首字母大写 (title())
s = 'abcdefgh'
print(s.title())
# 结果:Abcdefgh
六、字符串字母全变大写或小写 (upper())或(lower())
6.1 字符串字母全变大写
s = 'abcdefgh'
print(s.upper())
# 结果:ABCDEFGH
6.2 字符串字母全变小写
s = 'ABCDEFGH'
print(s.lower())
# 结果:abcdefgh
七、字符串空格的删除
7.1 strip() --->删除前后空格
s = ' 人生苦短, 我学Python! '
print(s.strip())
# 结果:人生苦短, 我学Python!
7.2 lstrip() --->删除左端空格
s = ' 人生苦短, 我学Python! '
print(s.lstrip())
# 结果:人生苦短, 我学Python!
7.3 rstrip() --->删除右端空格
s = ' 人生苦短, 我学Python! '
print(s.rstrip())
# 结果: 人生苦短, 我学Python!
7.4 使用replace()函数删除空格
s = ' 人生苦短, 我学Python! '
print(s.replace(' ',''))
# 结果:人生苦短,我学Python!
八、判断字符串是否全数字 (isdigit())
a = '123456789'
print(a.isdigit())
# 结果:True
九、使用join方法进行字符串的拼接
a = ['人生苦短,', '我学', 'Python!']
print(''.join(a))
# 结果:人生苦短,我学Python!
十、判断数据类型 (type())
a = ['人生苦短,', '我学', 'Python!']
print(type(a))
# 结果:<class 'list'>
今天就浅浅学到这里叭,下一篇写Python列表!