字符串的类型判断
是否字母或数字?isalnum
是否字母? isalpha
是否数字? isdigit
是否小写字母?islower
是否空格?isspace
是否标题? istitle
是否大写字母? issupper
是否十进制字符?isdecimal
小练习:判断变量的命名是否合法
变量名定义是否合法:
1.变量名可以由字母 数字 下划线组成
2.变量名只能以字母或者下划线开头
s = ‘321csv_’ s[0] s[1:]
s = ‘asfasf%%’
while True:
l=input(‘请输入一和变量名:’)
if l==‘exit’:
break
if l[0].isalpha() or l[0]’_’:
for i in l[1:]:
if not (i.isalnum() or i"_"):
print(‘变量不合法’)
break
else:
print(‘变量合法’)
else:
print(‘变量不合法’)
形式转换
lower 转换成小写字母
upper 转换成大写字母
title 转换成标题
swapcase 大小写反转
capitalize 转换成首字母大写,其他字母小写
‘hello’.istitle() #判断字符串是否是标题(首字母大写)
False
‘hello’.isupper() #判断字符串是否是大写(只要有一个元素是小写就会输出False)
False
‘HELLO’.isupper()
True
‘hello’.islower() #判断字符串是否是小写
True
‘Hello’.islower()
False
开头和结尾匹配
startwith() #是否以指定子字符串开头
endswith() #是否以指定子字符串结尾
filename = 'hello.log'
if filename.endswith('.log'):
print(filename)
else:
print('error.file')
url = 'http://172.25.254.14/index.html'
if url.startswith('http://'):
print('爬取内容')
else:
print('不能爬取内容')
数据清洗
strip #删除字符串开头和末尾的空格
lstrip #删除字符串开头尾的空格
rstrip #删除字符串末尾的空格
replace #字符串替换
s.lstrip() #hello字符串的左边是\t, lstrip()可以去除字符串左边的空格(\t)
s.lstrip() #hello字符串的左边是多个空格, lstrip()可以去除字符串左边的空格
s.lstrip() #hello字符串的左右两边都是多个空格, lstrip()可以去除字符串左边的空格, rstrip()可以去除字符串右边的空格, strip()可以去除字符串两边的空格
s.lstrip() #hello字符串的左边是一个制表位, lstrip()可以去除字符串左边的广义空格, strip()可以去除字符串两边的广义空格
s.lstrip() #hello字符串的左边是一个制表位,右边是一个换行符, lstrip()可以去除字符串左边的广义空格, strip()可以去除字符串两边的广义空格
s.strip() #helloh字符串strip('h')去掉字符串两边的h
s.strip() #helloh字符串lstrip('h')去掉字符串左边的h
搜索与统计
find(str,beg,end) #检测str是否包含在string中,返回索引
index(str,beg,end) #检测str是否包含在string中,返回索引,否则抛出异常
count(str.start,end) #检测str在string中出现的次数
s = 'hello world hello'
# find 找到子字符串,并返回最小的索引
print(s.find('hello'))
print(s.find('world'))
print(s.rfind('hello')) #找到子串,并返回最大的索引
#替换字符串中的hello为redhat
print(s.replace('hello','redhat'))
print('hello'.count('l'))统计字符串中l的个数
print('hello'.count('ll'))统计字符串中ll的个数
print(len('hello'))统计字符串的长度
位置调整
center(width) #字符串居中且长度为指定宽度
ljust(width) #字符串左对齐且长度为指定宽度
rjust(width) #字符串右对齐且长度为指定宽度
print('学生管理系统'.center(30)) #居中对齐,左右用空格填补,共占30个字符
print('学生管理系统'.center(30,'@')) #居中对齐,左右用@填补,共占30个字符
print('学生管理系统'.center(30,'&')) #居中对齐,左右用&填补,共占30个字符
print('学生管理系统'.ljust(30,'#')) #居左对齐,右侧用#填补,共占30个字符
print('学生管理系统'.rjust(30,'#')) #居右对齐,左边用#填补,共占30个字符
分离与拼接
split(str="") #以str为分隔符切片string,默认是空格
splitlines() #以分隔符切片string
join #将多个字符串拼接成一个字符串
s = '172.25.254.250'
s1 = s.split('.') #以.为分隔符分离字符串172.25.254.250
print(s1)
print(s1[::-1]) #将字符串反转
date = '2019-9-1'
date1 = date.split('-') #以"-"为分隔符分离字符串
print(date1)
连接
通过指定的连接符号 连接每个字符
print(''.join(date1)) #将分离的字符串连接起来
print('/'.join(date1)) #将分离的字符串以/为分隔符连接起来
print('~~'.join('hello')) #将hello字符串用~~连接起来
小练习:给定一个句子(只包含字母和空格), 将句子中的单词位置反转,单词用空格分割, 单词之间只有一个空格,前后没有空格。比如:(1) “hello xiao mi”-> “mi xiao hello”
其他内置方法
len() #返回字符串的字符数
max() and min() #返回最大或者最小的字符,(按照 ASCII 码值排列)