字符串的常用方法
字符串是Python中的不可变数据类型,在Python中一切皆对象,字符串对象本身就有一些常用的方法。
字符串的常用操作:
案例:
# 大小写转换。lower()、upper()都会返回新的字符串
s1 = 'HelloWorld'
new_s2 = s1.lower()
print(s1, new_s2)
new_s3 = s1.upper()
print(s1, new_s3)
# 字符串的分隔。split()返回列表类型
e_mail = 'lxl@163.com'
lst = e_mail.split('@')
print('邮箱名:', lst[0], '邮件服务器名:', lst[1])
# 统计子串出现的次数
print(s1.count('o'))
# 检索操作
print(s1.find('o')) # o在字符串s1中首次出现的位置
print(s1.find('p')) # -1,表示没有找到
print(s1.index('o'))
# print(s1.index('p')) # ValueError: substring not found
# 判断前缀和后缀
print(s1.startswith('H')) # True
print(s1.startswith('P')) # False
print('demo.py'.endswith('.py')) # True
print('text.txt'.endswith('.txt')) # True
格式化字符串
前面提到使用 + 号可以进行字符串的连接,但仅限于字符串与字符串之间的连接,不能将字符串与其他数据类型进行连接。而引入了格式化字符串后就可以将字符串与其他数据类型进行连接。
格式化字符串的三种方式:
1、占位符 (类似C语言,这里只列出三种,实际上有很多)
%s:字符串格式
%d:十进制整数格式
%f:浮点数格式
2、f-string
Python 3.6 引入的格式化字符串的方式,以 { } 标明被替换的字符
3、str.format()方法
模版字符串.format(逗号分隔的参数)
案例:
# 1、使用占位符进行格式化
name = '马冬梅'
age = 18
score = 98.5
print('姓名:%s,年龄:%d,成绩:%f' % (name, age, score)) # 元组
print('姓名:%s,年龄:%d,成绩:%.1f' % (name, age, score)) # %.1f表示保留一位小数
# f-string
print(f'姓名:{name},年龄:{age},成绩:{score}')
# 字符串的format方法
# 0、1、2对应的是format当中参数的索引位置
print('姓名:{0},年龄:{1},成绩:{2}'.format(name, age, score))
print('姓名:{2},年龄:{0},成绩:{1}'.format(age, score, name))
format详细格式控制
使用字符串 format( ) 方法有更加精细的控制输出格式。
格式化字符串的详细格式:
其中"类型"中 e\E 表示科学计数法;f 表示精度;%表示百分数。
案例:
s = 'helloworld'
print('{0:*<20}'.format(s)) # 字符串的显示宽度为20,左对齐,空白部分使用*填充
print('{0:*>20}'.format(s)) # 右对齐
print('{0:*^20}'.format(s)) # 居中对齐
# 居中对齐还有center()方法
print(s.center(20, '*'))
# 千位分隔符(只适用于整数和浮点数)
print('{0:,}'.format(987654321))
print('{0:,}'.format(987654321.4321))
# 浮点数小数部分的精度
print('{0:.2f}'.format(3.1415926))
# 字符串类型,表示是最大的显示长度
print('{0:.5}'.format('helloworld'))
# 整数类型
a = 425
print('二进制:{0:b},十进制:{0:d},八进制:{0:o},十六进制:{0:x},十六进制{0:X}'.format(a))
# 浮点数类型
b = 3.1415926
print('{0:.2f},{0:.2e},{0:.2E},{0:.2%}'.format(b))
字符串编解码
字符串的编码:
将str类型转换成bytes类型,需要使用到字符串的encode()方法。
语法格式:
str.encode( encoding = ‘utf-8’, errors = ‘strict/ignore/replace’ )
字符串的解码:
将bytes类型转换成str类型,需要使用到bytes类型的decode()方法。
语法格式:
bytes.decode(encoding = ‘utf-8’, errors = ‘strict/ignore/replace’ )
- ignore:忽略。
- strict:严格的。遇到转不了的字符程序直接报错。
- replace:替换。遇到转不了的字符程序会使用 ? 替换无法转换的字符。
案例:
s = '伟大的中国梦'
# 编码 str-->bytes
scode = s.encode(errors='replace') # 默认的编码格式是 utf-8。在utf-8中文占3个字节
print(scode)
scode_gbk = s.encode('gbk', errors='replace') # gbk中文占2个字节
print(scode_gbk)
# 解码 bytes-->str
print(scode_gbk.decode('gbk', errors='replace'))
print(bytes.decode(scode_gbk, 'gbk'))
print(bytes.decode(scode, 'utf-8'))
数据验证的方法
案例:
# isdigit()只能识别十进制的阿拉伯数字
print('123'.isdigit()) # True
print('0b1010'.isdigit()) # 二进制 False
print('一二三四'.isdigit()) # 中文数字 False
print('IIIIII'.isdigit()) # 罗马数字 False
print('-' * 50)
# 所有字符都是数字。isnumeric()能识别阿拉伯数字、罗马数字、中文数字
print('123'.isnumeric()) # True
print('一二三四'.isnumeric()) # True
print('Ⅰ'.isnumeric()) # True
print('0b1010'.isdigit()) # False
print('壹贰叁'.isnumeric()) # True
print('-' * 50)
# 所有字符都是字母(包含中文字符)
print('hello你好'.isalpha()) # True
print('hello你好123'.isalpha()) # False
print('hello你好一二三'.isalpha()) # True
print('hello你好ⅠⅡⅢ'.isalpha()) # False
print('hello你好壹贰叁'.isalpha()) # True
print('-' * 50)
# 所有字符都是数字或字母(包含中文字符)
print('hello你好'.isalnum()) # True
print('hello你好123'.isalnum()) # True
print('hello你好一二三'.isalnum()) # True
print('hello你好ⅠⅡⅢ'.isalnum()) # True
print('hello你好壹贰叁'.isalnum()) # True
print('-' * 50)
# 判断字符的大小写
print('HelloWorld'.islower()) # False
print('helloworld'.islower()) # True
print('hello你好'.islower()) # True
print('-' * 50)
print('HelloWorld'.isupper()) # False
print('HELLOWORLD'.isupper()) # True
print('HELLO你好'.isupper()) # True
print('-' * 50)
# 所有字符都是首字母大写。当且仅当首字母是大写时返回True,如存在非首字母大写则会返回False
print('HelloWorld'.istitle()) # False 。存在非首字母大写,故返回False
print('Helloworld'.istitle()) # True
print('Hello World'.istitle()) # True 。这里是两个单词
print('Hello world'.istitle()) # False 。这里是两个单词,第二个单词的首字母没有大写
print('-' * 50)
# 判断是否都是空白字符
print('\t'.isspace()) # True
print(' '.isspace()) # True
print('\n'.isspace()) # True
字符串的拼接操作
前面提到可以使用 + 号拼接字符串。还有以下三种方式拼接字符串:
1、使用str.join()方法进行拼接字符串
2、直接拼接
3、使用格式化字符串进行拼接
案例:
s1 = 'hello'
s2 = 'world'
# 使用+进行拼接
print(s1 + s2)
# 使用字符串join()方法
# 把s1、s2放在一个列表中,join()会对列表当中的元素进行一个拼接
print(''.join([s1, s2])) # 使用空字符串进行拼接
print('*'.join(['hello', 'world', 'python', 'java', 'php']))
print('你好'.join(['hello', 'world', 'python', 'java', 'php']))
# 直接拼接
print('hello''world')
# 使用格式化字符串进行拼接
print('%s%s' % (s1, s2))
print(f'{s1}{s2}')
print('{0}{1}'.format(s1, s2))
字符串的去重操作
# 字符串去重操作
s = 'helloworldhelloworlddlrowolleh'
# 使用字符串拼接及not in
new_s = ''
for item in s:
if item not in new_s:
new_s += item # 拼接操作
print(new_s)
# 使用索引+ not in
new_s2 = ''
for i in range(len(s)):
if s[i] not in new_s2: # 索引
new_s2 += s[i] # 拼接操作
print(new_s2)
# 通过集合去重+列表排序
# 集合的性质:唯一性、无序性。因此转换成集合后需要将其按照原来的顺序进行排序
new_s3 = set(s)
lst = list(new_s3)
lst.sort(key=s.index) # 作为参数不能有(),调用时才有()
print(''.join(lst)) # 使用join()方法进行字符串拼接
正则表达式
正则字符
re模块
re模块:
Python中的内置模块,用于实现Python中的正则表达式操作。
match函数
import re # 导入re模块
# match()用于从字符串的开始位置进行匹配,如果起始位置匹配成功,结果为Match对象,否则结果为None
pattern = '\d\.\d+' # + 限定符,\d 0-9 数字出现1次或多次
s = 'I study Python 3.11 every day' # 待匹配字符串
match = re.match(pattern, s, re.I) # re.I表示忽略大小写,Ignore
print(match) # None
s2 = '3.11 Python I study every day'
match2 = re.match(pattern, s2)
print(match2) # <re.Match object; span=(0, 4), match='3.11'> ,指[0,4)
print('匹配值的起始位置:', match2.start())
print('匹配值得结束位置:', match2.end())
print('匹配区间的位置元素:', match2.span())
print('待匹配的字符串:', match2.string)
print('匹配的数据:', match2.group())
search函数和findall函数
search()函数的使用:
import re # 导入re模块
# search()用于在整个字符串中国搜索第一个匹配的值,如果匹配成功,结果为Match对象,否则结果为None
pattern = '\d\.\d+' # + 限定符,\d 0-9 数字出现1次或多次
s = 'I study Python3.11 every day Python2.7 I love you' # 待匹配字符串
match = re.search(pattern, s)
print(match)
s2 = '3.10Python I love you'
match2 = re.search(pattern, s2)
print(match2)
s3 = 'I study Python every day'
match3 = re.search(pattern, s3)
print(match3) # None
print(match.group())
print(match2.group())
findall()函数的使用:
import re # 导入re模块
# findall()用于在整个字符串搜索所有符合正则表达式的值,结果是一个列表类型
pattern = '\d\.\d+' # + 限定符,\d 0-9 数字出现1次或多次
s = 'I study Python3.11 every day Python2.7 I love you' # 待匹配字符串
s2 = 'I study Python3.10 every day'
s3 = 'I study Python'
lst = re.findall(pattern, s)
lst2 = re.findall(pattern, s2)
lst3 = re.findall(pattern, s3)
print(lst)
print(lst2)
print(lst3)
常用正则匹配
IP地址
import re
ip_regex = r'\b(?:\d{1,3}\.){3}\d{1,3}\b'
test_string = "这是一个IP地址:192.168.1.1,另一个是:10.0.0.1"
ip_addresses = re.findall(ip_regex, test_string)
print(ip_addresses)
# ['192.168.1.1', '10.0.0.1']
邮件地址
import re
email_regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
email_string = "邮件地址:18847097110@163.com, john.doe@outlook.com"
email_addresses = re.findall(email_regex, email_string)
print(email_addresses)
# ['18847097110@163.com', 'john.doe@outlook.com']
原文链接:第六章 字符串及正则表达式-优快云博客