1.判断字符串里每个元素是否为什么类型
判断的标准为:一旦有一个元素不满足,就返回False
(1): isdigit(),判断是不是数字
print('123'.isdigit())
print('123abc'.isdigit())
上述代码的输出结果:
(2): istitle() 判断某个字符串是否为标题(第一个字母大写,其余字母小写)
print('Hello'.istitle())
print('HeLlo'.istitle())
上述代码的输出结果:
(3): upper()将转换为大写字母,isupper()判断是否为大写字母
print('hello'.upper())
print('hello'.isupper())
上述代码的输出结果:
(4): lower()将转换为小写字母,islower()判断是否为小写字母
print('HELLO'.lower())
print('HELLO'.islower())
上述代码的输出结果:
(5): 判断是否为数字和字母
print('hello123'.isalnum()) #是否为数字和字母
print('123'.isalpha()) #是否为字母
print('aaa'.isalpha())
上述代码的输出结果:
2.字符串开头结尾的匹配
(1):endswith()匹配结尾
filename = 'hello.loggg'
if filename.endswith('.log'):
print(filename)
else:
print('error filename')
上述代码的输出结果:
此程序输出error filename,如果将字符串filename改为hello.log时,就会输出hello.log
(2):startswith()匹配开头
url1 = 'file:///mnt'
url2 = 'ftp://172.25.254.250/pub'
url3 = 'https://172.25.254.250/index.html'
if url3.startswith('http://'):
print('获取网页')
else:
print('未找到网页')
此程序输出为‘未找到网页’
3.字符串去掉两边空格
这里需要使用到strip()命令
s.strip() ##去掉两边空格
s.rstrip() ##去掉右面空格
s.lstrip() ##去掉左边空格
实验:
s = ' hello '
print(s.strip())
print(s.rstrip())
print(s.lstrip())
上述代码的输出结果:
我们也可以那此方法去掉字符串中的字母
4.字符串的搜索与替换
s = 'hello world hello'
print(s.find('hello')) #find找到子串,并返回最小的索引
print(s.find('world'))
print(s.rfind('hello')) #rfind找到子串,并返回最大索引
print(s.replace('hello','westos')) #替换字符串中所有的'hello'为'westos'
上述代码的输出结果:
5.字符串的对齐
print('学生管理系统'.center(30)) #中间对齐,其他位置填充空格
print('学生管理系统'.center(30,'*')) #中间对齐,其他位置填充*
print('学生管理系统'.ljust(30,'*')) #左边对齐,其他位置填充*
print('学生管理系统'.rjust(30,'*')) #右边对齐,其他位置填充*
print('学生管理系统'.rjust(30,'@')) #右边对齐,其他位置填充@
上述代码的输出结果:
6.字符串的统计
print('hello'.count('l'))
print('hello'.count('ll'))
print(len('hello'))
上述代码的输出结果:
7.字符串的分离和连接
split()分离,join()连接,括号内表示的是以什么为分隔符,或者以什么为连接符
date = '2019-01-15'
date1 = date.split('-') ##以-为分割符
print(date1)
print(''.join(date1))
print('/'.join(date1)) ##以/为连接符
上述代码的输出结果:
快速生成验证码
import random
import string
code_str = string.ascii_letters + string.digits
#print(code_str)
def gen_code(len=4):
return ''.join(random.sample(code_str,len))
print(gen_code())
上述代码的输出结果: