目录
- 一、初始化
- 二、索引
- 三、常用操作
- 3.1 拼接字符串
- 3.2 检索字符串
- 3.3 分割
- 3.4 替换 replace() 方法——替换字符串
- 3.5 移除 strip() 方法——去除字符串头尾特殊字符
- 3.6 判断
- 3.6.1 startswith()方法——是否以指定的子字符串开头
- 3.6.2 endswith()方法——是否以指定子字符串结尾
- 3.6.3 isalnum()方法——判断字符串是否由字母和数字组成
- 3.6.4 isalpha()方法——判断字符串是否只由字母组成
- 3.6.5 isdecimal()方法——判断字符串是否只包含十进制字符
- 3.6.6 isdigit()方法——判断字符串是否只由数字组成
- 3.6.7 isidentifier()方法——判断字符串是否为合法的Python标识符或变量名
- 3.6.8 islower()方法——判断字符串是否全由小写字母组成
- 3.6.9 isnumeric()方法——判断字符串是否只由数字(支持罗马数字、汉字数字等)组成
- 3.6.10 isprintable()方法——判断字符是否为可打印字符
- 3.6.11 isspace()方法——判断字符串是否只由空格组成
- 3.6.12 istitle()方法——判断首字母是否大写其他字母小写
- 3.6.13 isupper()方法——判断字符串是否全由大写字母组成
- 3.7 字符串转换方法(用的少)
- 3.8 字符对齐方法(用的少)
- 四、编码与解码
- 五、切片
- 六、格式化字符串
字符串(String)是编程中最基础、最常用的数据类型之一。本篇将系统讲解 Python 中字符串的创建与常用方法(替换、分割、查找、判断等),深入剖析三种字符串格式化方法,同时引导你理解编码的本质——二进制世界,正式认识字节类型(bytes),掌握字符串与字节的相互转换技巧。此外,还会重点讲解切片(slice),掌握切片后,你将可以灵活操作任意字符串数据。
一、初始化
一个个字符组成的有序的序列,是字符的集合。使用单引号、双引号、三引号引住的字符序列,字符串是不可变对象,是字面常量,Python3 起,字符串都是 Unicode 类型。示例代码:
s1 = 'string'
s2 = "string2"
s3 = '''this's a "String" '''
s4 = 'hello \n blog.csdn.net'
s5 = r"hello \n blog.csdn.net"
s6 = 'c:\windows\nt'
s7 = R"c:\windows\nt"
s8 = 'c:\windows\\nt'
name = 'tom'; age = 20 # python代码写在一行,使用分号隔开,不推荐
s9 = f'{name}, {age}' # 3.6支持f前缀
sql = """select * from user where name='amo' """
r
前缀:所有字符都是本来的意思,没有转义
f
前缀:3.6 开始,使用变量插值
二、索引
字符串是序列,支持下标访问。但不可变,不可以修改元素。示例代码:
sql = "select * from user where name='amo'"
print(sql[4]) # 字符串'c'
# sql[4] = 'o' # 不可以 TypeError: 'str' object does not support item assignment
三、常用操作
3.1 拼接字符串
3.1.1 "+"号
使用 "+"
运算符可完成对多个字符串的拼接,"+"
运算符可以连接多个字符串并产生一个新的字符串对象。示例代码:
mot_en = 'Remembrance is a form of meeting. Forgetfulness is a form of freedom.'
mot_cn = '记忆是一种相遇。遗忘是一种自由。'
print(mot_en + '――' + mot_cn)
str1 = '我今天一共走了' # 定义字符串
num = 12098 # 定义一个整数
str2 = '步' # 定义字符串
# 报错: 字符串不允许直接与其他类型的数据拼接,TypeError: can only concatenate str (not "int") to str
# print(str1 + num + str2) # 对字符串和整数进行拼接
# 正确示例: 先将num转换为字符串,在进行拼接
print(str1 + str(num) + str2)
3.1.2 join()方法
join() 方法用于连接字符串列表。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串,例如下图所示:
join() 方法的语法如下:
In [1]: str.join?
Signature: str.join(self, iterable, /)
Docstring:
Concatenate any number of strings.
The string whose method is called is inserted in between each given string.
The result is returned as a new string.
Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
Type: method_descriptor
参数说明:
str:分隔符,即用什么连接字符串,可以是逗号","、冒号":"、分号";"和斜杠"/"等等,也可以为空
iterable:要连接的可迭代对象。可以是字符串、字符串数组、列表、元组或字典等
注意,join() 方法要求可迭代对象中的所有元素都是字符串类型。如果元素是非字符串类型(如数字),需要先将其转换为字符串。
示例代码:
# 用空格连接字符串中的字符
word = 'Python'
spaced_word = ' '.join(word)
print(spaced_word) # P y t h o n
# 用逗号连接字符串中的字符
word = 'Hello'
comma_separated = ','.join(word)
print(comma_separated) # H,e,l,l,o
# 用下划线连接字符串中的字符
word = 'OpenAI'
underscore_separated = '_'.join(word)
print(underscore_separated) # O_p_e_n_A_I
# 用无分隔符连接字符串中的字符(其实是保持原字符串不变)
word = 'ChatGPT'
no_separator = ''.join(word)
print(no_separator) # ChatGPT
# print(''.join([1, 2, 3, 4, 5])) # TypeError: sequence item 0: expected str instance, int found
print(''.join(map(str, [1, 2, 3, 4, 5]))) # 12345
# 连接字符串列表
s = ['四', '川', '大', '学']
print(''.join(s)) # 四川大学
print('-'.join(s)) # 四-川-大-学
print('/'.join(s)) # 四/川/大/学
music = ['辞九门回忆', '会不会', '单身情歌', '错位时空', '红色高跟鞋']
print(music)
print(' '.join(music))
print('\n'.join(music))
print('\t'.join(music))
# 定义字典
my_str = {'四': 1, '川': 2, '大': 3, '学': 4}
print(':'.join(my_str)) # 四:川:大:学
3.2 检索字符串
3.2.1 find() 方法——字符串首次出现的索引位置(rfind()、index()、rindex())
find() 方法实现查询一个字符串在其本身字符串对象中首次出现的索引位置,如起始位置从 11 到结束位置 17 之间子字符串出现的位置,如下图所示。如果没有检索到该字符串,则返回-1。
find() 方法的语法格式如下:
In [2]: str.find?
Docstring:
S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
Type: method_descriptor
参数说明:
str:表示原字符串。
sub:表示要检索的子字符串。
start:可选参数,表示检索范围的起始位置的索引,如果不指定,则从头开始检索。
end :可选参数,表示检索范围的结束位置的索引,如果不指定,则一直检索到结尾。
例如,子字符串 o
在字符串 www.mingrisoft.com
起始位置从 11
到结束位置 17
之间首次出现的位置,如下图所示:
说明:Python 的字符串对象还提供了 rfind() 方法,其作用与 find() 方法类似,只是从字符串右边开始查找。Python 的字符串也提供了 index() 方法,它与 find() 方法功能相同,区别在于当 find() 方法没有检索到字符串时会返回 -1,而 index() 方法会抛出 ValueError 异常。
示例代码:
# 1.检索邮箱地址中"@"首次出现中的位置
qq_email = '123456789@qq.com'
print(qq_email.find('@')) # 9
print(qq_email.find('Q')) # -1
# 2.提取括号内数据
str1 = '张三(13566688888)'
l1 = str1.find('(')
l2 = str1.find(')')
print(str1[l1 + 1:l2]) # 13566688888
# 3.从邮箱地址提取ID并将首字母大写
email_list = ['gcytom@sohu.com', 'jackeer@qq.com', 'mingrisoft@mingrisoft.com', 'mrkj_2019@qq.com']
for _email in email_list:
print(_email[:_email.find('@')].capitalize())
# 4.查询字符串中指定字符的全部索引
str_index_list = [] # 保存指定字符的索引
def get_multiple_indexes(string, s):
str2 = string # 用于获取字符串总长度
while True: # 循环
if s in string: # 判断是否存在需要查找的字符
first_index = string.index(s) # 获取字符串中第一次出现的字符对应的索引
string = string[first_index + 1:] # 将每次找打的字符从字符串中截取掉
result = len(str2) - len(string) # 计算截取部分的长度
str_index_list.append(result - 1) # 长度减1就是字符所在的当前索引,将索引添加列表中
else:
break # 如果字符串中没有需要查找的字符就跳出循环
print(str_index_list) # 打印指定字符出现在字符串中的全部索引
# [0, 1, 2, 8]
get_multiple_indexes("aaabbdddabb", 'a') # 调用自定义方法,获取字符串中指定字符的全部索引
# 其他方法示例
s1 = 'www.mingrisoft.com'
substr = 'm'
print(s1.rfind(substr)) # 17
print(s1.rfind(substr, 0, 5)) # 4
print(s1.rfind(substr, 5, 0)) # -1
str1 = '790129881@qq.com'
print('@符号首次出现的位置为:', str1.index('@')) # 9
s2 = 'www.mingrisoft.com'
substr = 'm'
print(s2.rindex(substr)) # 17
print(s2.rindex(substr, 0, 5)) # 4
# print(s2.rindex(substr, 5, 0)) # ValueError: substring not found
rfind() 方法返回子字符串在字符串中最后一次出现的位置(从右向左查询),如果没有匹配项则返回-1。rindex() 方法的作用与 index() 方法类似。rindex() 方法用于查询子字符串在字符串中最后出现的位置,如果没有匹配的字符串会报异常。另外,还可以指定开始位置和结束位置来设置查找的区间。 这两个方法效率真不高,都是在字符串中遍历搜索,但是如果找子串工作必不可少,那么必须这么做,但是能少做就少做。
3.2.2 count() 方法——统计字符串出现次数
count() 方法用于统计字符串中某个字符出现的次数,如起始位置从 11 到结束位置 17 之间字符出现的次数,如下图所示:
count() 方法的语法格式如下:
In [3]: str.count?
Docstring:
S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are
interpreted as in slice notation.
Type: method_descriptor
参数说明:
S:表示原字符串。
sub:表示要检索的子字符串。
start:可选参数,表示检索范围的起始位置的索引,默认为第一个字符,索引值为 0,可单独指定。
end:可选参数,表示检索范围的结束位置的索引,默认为字符串的最后一个位置,不可以单独指定。
例如,子字符串 o
在字符串 www.mingrisoft.com
起始位置从 11
到结束位置 17
之间中出现的次数,如下图所示:
注意:这里要注意一点,结束位置为17,但是统计字符个数时不包含17这个位置上的字符。例如结束位置为 16,那么o出现的次数为1。
示例代码:
import string
# 获取关键词"人民"在字符串中出现的次数
str1 = ('五四运动,爆发于民族危难之际,是一场以先进青年知识分子为先锋、'
'广大人民群众参加的彻底反帝反封建的伟大爱国革命运动,是一场中国人民为拯救民族危亡、'
'捍卫民族尊严、凝聚民族力量而掀起的伟大社会革命运动,是一场传播新思想新文化新知识的伟大思想启蒙运动和新文化运动'
',以磅礴之力鼓动了中国人民和中华民族实现民族复兴的志向和信心。')
print('这句话中"人民"共出现:', str1.count('人民'), '次')
# 统计关键词在字符串中不同位置处出现的次数
cn = '没什么是你能做却办不到的事。'
en = "There's nothing you can do that can't be done."
print(cn)
print('原字符串:', en)
# 字母"o"在不同位置处出现的次数
print(en.count('o', 0, 17)) # 1
print(en.count('o', 0, 27)) # 3
print(en.count('o', 0, 47)) # 4
count = 0
test_str = "https://blog.csdn.net/xw1680%$&,*,@!"
# 将输入的字符串创建一个新字典
c = {}.fromkeys(test_str, 0) # 将字符串中的每个字符作为key,对应的值为0
for key, value in c.items():
if key in string.punctuation: # 统计标点符号
count = test_str.count(key) + count
# 字符串中包含: 14 个标点符号
print('字符串中包含:', count, '个标点符号')
# 统计文本中数字出现的个数
f = open('./digits.txt', 'r', encoding='utf-8')
chars = f.read()
count = 0
# 将输入的字符串创建一个新字典
c = {}.fromkeys(chars, 0)
for key, value in c.items():
if key in string.digits: # 统计数字
count = chars.count(key) + count
print('文本中包含:', count, '个数字') # 14
find、index 和 count 方法都是 O(n),随着字符串数据规模的增大,而效率下降。
3.2.3 len() 函数——计算字符串长度或元素个数
len() 函数的主要功能是获取一个(字符、列表、元组等)可迭代对象的长度或项目个数。其语法格式如下:
In [4]: len?
Signature: len(obj, /)
Docstring: Return the number of items in a container.
Type: builtin_function_or_method
参数说明:
参数obj:要获取其长度或者项目个数的对象。如字符串、元组、列表、字典等;
返回值:对象长度或项目个数。
示例代码:
# 1.获取字符串长度
# 字符串中每个符号仅占用一个位置,所以该字符串长度为34
str1 = '今天会很残酷,明天会更残酷,后天会很美好,但大部分人会死在明天晚上。'
# 在获取字符串长度时,空格也需要占用一个位置,所以该字符串长度为11
str2 = 'hello world'
print('str1字符串的长度为:', len(str1)) # 打印str1字符串长度 34
print('str2字符串的长度为', len(str2)) # 打印str2字符串长度 11
# 打印str2字符串去除空格后的长度
print('str2字符串去除空格后的长度为:', len(str2.replace(' ', ''))) # 10
# 2.计算字符串的字节长度
def byte_size(string):
return len(string.encode('utf-8')) # 使用encode()函数设置编码格式
print(byte_size('Hello World')) # 11
print(byte_size('人生苦短,我用Python')) # 27
"""
说明:在utf-8编码格式下,一个中文占3个字节。
"""
3.3 分割
3.3.1 split() 方法——分割字符串
split() 方法可以把一个字符串按照指定的分隔符切分为字符串列表,例如下图所示的效果。该列表的元素中,不包括分隔符。
split() 方法的语法格式如下:
In [6]: str.split?
Signature: str.split(self, /, sep=None, maxsplit=-1)
Docstring:
Return a list of the substrings in the string, using sep as the separator string.
sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace
character (including \\n \\r \\t \\f and spaces) and will discard
empty strings from the result.
maxsplit
Maximum number of splits (starting from the left).
-1 (the default value) means no limit.
Note, str.split() is mainly useful for data that has been intentionally
delimited. With natural text that includes punctuation, consider using
the regular expression module.
Type: method_descriptor
参数说明:
str:表示要进行分割的字符串。
sep:用于指定分隔符,可以包含多个字符,默认为 None,即所有空字符(包括空格、换行"\n"、制表符"\t"等)。
maxsplit:可选参数,用于指定分割的次数,如果不指定或者为-1,则分割次数没有限制,否则返回结果列表的元素个数,
个数最多为 maxsplit+1。
返回值:分隔后的字符串列表。
在使用split()方法时,如果不指定参数,默认采用空白符进行分割,这时无论有几个空格或者空白符都将作为一个分隔符进行分割。
示例代码:
# 1.根据不同的分隔符分割字符串
str1 = 'www.baidu.com'
list1 = str1.split() # 采用默认分隔符进行分割
list2 = str1.split('.') # 采用.号进行分割
list3 = str1.split(' ', 1) # 采用空格进行分割,并且只分割第1个
print(list1) # ['www.baidu.com']
print(list2, list2[1]) # ['www', 'baidu', 'com'] baidu
print(list3) # ['www.baidu.com']
# 2.删除字符串中连续多个空格而保留一个空格
line = '吉林省 长春市 二道区 东方广场中意之尊888'
# 吉林省 长春市 二道区 东方广场中意之尊888
print(' '.join(line.split()))
s = ','.join('abcd') # 'a,b,c,d'
print(s.split(',')) # ['a', 'b', 'c', 'd']
print(s.split()) # ['a,b,c,d']
print(s.split(',', 2)) # ['a', 'b', 'c,d']
s1 = '\na b \tc\nd\n' # 注意下面3个切割的区别print(s1.split())
s2 = ',a,b,c,d,'
print(s1.split()) # ['a', 'b', 'c', 'd']
print(s2.split(',')) # ['', 'a', 'b', 'c', 'd', '']
print(s1.split(' ')) # ['\na', 'b', '', '\tc\nd\n']
print(s1.split('\n')) # ['', 'a b \tc', 'd', '']
print(s1.split('b')) # ['\na ', ' \tc\nd\n']
print(s1.splitlines()) # ['', 'a b \tc', 'd']
rsplit() 也是 Python 中用于分割字符串的一个方法,与 split() 类似,但它从字符串的右侧开始分割。它主要用于从右侧开始分割字符串,并返回一个列表。对比 split,示例代码如下:
# 1.不指定 maxsplit 参数
text = "apple, banana, cherry, date"
split_result = text.split(", ")
rsplit_result = text.rsplit(", ")
print("split:", split_result) # split: ['apple', 'banana', 'cherry', 'date']
print("rsplit:", rsplit_result) # split: ['apple', 'banana', 'cherry', 'date']
# 2.指定 maxsplit=2
text = "apple, banana, cherry, date"
split_result = text.split(", ", 2)
rsplit_result = text.rsplit(", ", 2)
print("split:", split_result) # split: ['apple', 'banana', 'cherry, date']
print("rsplit:", rsplit_result) # rsplit: ['apple, banana', 'cherry', 'date']
# 3.处理末尾带有空白符的字符串
text = "a b c d "
split_result = text.split(" ", 2)
rsplit_result = text.rsplit(" ", 2)
print("split:", split_result) # split: ['a', 'b', 'c d ']
print("rsplit:", rsplit_result) # rsplit: ['a b c', 'd', '']
# 4.多个空格作为分隔符
text = " one two three "
split_result = text.split()
rsplit_result = text.rsplit()
# ps:当字符串两端存在空格且不指定 sep 参数时,split() 和 rsplit() 的行为相同,都会忽略两端的空格。
print("split:", split_result) # split: ['one', 'two', 'three']
print("rsplit:", rsplit_result) # rsplit: ['one', 'two', 'three']
3.3.2 splitlines()方法——返回是否包含换行符的列表
splitlines() 方法用于按照换行符 \r,\r\n,\n
分隔,返回一个是否包含换行符的列表,如果参数 keepends 为 False,则不包含换行符,如果为 True,则包含换行符。splitlines() 方法的语法格式如下:
In [11]: str.splitlines?
Signature: str.splitlines(self, /, keepends=False)
Docstring:
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and
true.
Type: method_descriptor
参数说明:
keepends:输出结果是否包含换行符 (\r,\r\n,\n),默认值为False,不包含换行符,如果为True,则保留换行符
返回值:返回一个包含换行符的列表
示例代码:
str1 = 'Amo\r\nPaul\r\nJerry'
s1 = '\na b \tc\nd\n'
list1 = str1.splitlines() # 不带换行符的列表
print(list1) # ['Amo', 'Paul', 'Jerry']
print(list1[0], list1[1], list1[2]) # Amo Paul Jerry
list2 = str1.splitlines(True) # 带换行符的列表
print(list2) # ['Amo\r\n', 'Paul\r\n', 'Jerry']
print(list2[0], list2[1], list2[2], sep='') # 使用sep去掉空格
print(s1.splitlines()) # ['', 'a b \tc', 'd']
# 一些复杂一点的案例
# 1.字符串包含多种换行符(\n, \r\n, \r)
text = ' Line 1\nLine 2\r\nLine 3\rLine 4 '
lines = text.splitlines()
print(lines) # [' Line 1', 'Line 2', 'Line 3', 'Line 4 ']
# 2.包含空行和多种空白符(如制表符和空格)
text = '\tLine 1\n\n \r\nLine 2\t\n\r\tLine 3 '
lines = text.splitlines() # ['\tLine 1', '', ' ', 'Line 2\t', '', '\tLine 3 ']
print(lines)
# 3.保留换行符的情况下分割
text = ' Line 1\n\tLine 2\r\n \tLine 3\rLine 4 '
lines = text.splitlines(keepends=True)
print(lines) # [' Line 1\n', '\tLine 2\r\n', ' \tLine 3\r', 'Line 4 ']
# 4.处理两端有空白符的字符串
text = '\n\n \t Line 1\n Line 2 \n \n'
lines = text.splitlines()
print(lines) # ['', '', ' \t Line 1', ' Line 2 ', ' ']
# 5.仅包含空白符的字符串
text = ' \t '
lines = text.splitlines()
print(lines) # [' \t ']
3.3.2 partition()方法——分割字符串为元组
partition() 方法根据指定的分隔符将字符串进行分割。如果字符串中包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子字符串,第二个为分隔符本身,第三个为分隔符右边的子字符串,如下图所示:
partition() 方法的语法格式如下:
In [12]: str.partition?
Signature: str.partition(self, sep, /)
Docstring:
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found,
returns a 3-tuple containing the part before the separator, the separator
itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string
and two empty strings.
Type: method_descriptor
示例代码:
python_url = 'https://blog.csdn.net/xw1680?' # 定义字符串
t1 = python_url.partition('.') # 以"."分割
# ('https://blog', '.', 'csdn.net/xw1680?')
print(t1)
s = ','.join('abcd') # 'a,b,c,d'
print(s.partition(',')) # ('a', ',', 'b,c,d')
print(s.partition('.')) # ('a,b,c,d', '', '')
print(s.rpartition(',')) # ('a,b,c', ',', 'd')
print(s.rpartition('.')) # ('', '', 'a,b,c,d')
rpartition() 方法与 partition() 方法基本一样,细微区别在于 rpartition() 方法是从目标字符串的末尾也就是右边开始搜索分割符。
3.4 替换 replace() 方法——替换字符串
replace() 方法用于将某一字符串中一部分字符替换为指定的新字符,如果不指定新字符,那么原字符将被直接去除,例如图1和图2所示的效果。
replace() 方法的语法格式如下:
In [13]: str.replace?
Signature: str.replace(self, old, new, count=-1, /)
Docstring:
Return a copy with all occurrences of substring old replaced by new.
count
Maximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are
replaced.
Type: method_descriptor
参数说明:
str: 要替换的字符串
old: 将被替换的子字符串。
new: 字符串,用于替换old子字符串。
count: 可选参数,表示要替换的次数,如果不指定该参数则替换所有匹配字符,而指定替换次数时的替换顺序是从左向右依次替换。
示例代码:
str1 = 'www.baidu.com'
# www.douban.com
print(str1.replace('baidu', 'douban'))
str1 = '333333201501012222'
s1 = str1[6:14]
# 333333********2222
print(str1.replace(s1, '********'))
s = ','.join('abcd') # 'a,b,c,d'
print(s.replace(',', ' ')) # 'a b c d'
print(s.replace(',', ' ', 2)) # 'a b c,d'
s1 = 'www.baidu.com'
print(s1.replace('w', 'a')) # 'aaa.baidu.com'
print(s1.replace('ww', 'a')) # 'aw.baidu.com'
print(s1.replace('ww', 'w')) # 'ww.baidu.com'
3.5 移除 strip() 方法——去除字符串头尾特殊字符
strip() 方法用于移除字符串左右两边的空格和特殊字符,例如下图所示的效果:
strip() 方法的语法格式如下:
In [15]: str.strip?
Signature: str.strip(self, chars=None, /)
Docstring:
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
Type: method_descriptor
参数说明:
str:原字符串。
chars:为可选参数,用于指定要去除的字符,可以指定多个。
例如,设置chars为 `*`,则去除左、右两侧包括的`*`。
如果不指定 chars 参数,默认将去除字符串左右两边的空格、制表符 `\t`、回车符 `\r`、换行符 `\n` 等。
示例代码:
# 去除字符串中的空格
s1 = ' hello world '
print(s1.strip(' ')) # 去除字符串中头尾的空格
s2 = (' add_sheet会返回一个Worksheet类。创建的时候有可选参数cell_overwrite_ok,'
'表示是否可以覆盖单元格,其实是Worksheet实例化的一个参数,默认值是False。去除字符串中的特殊字符\t\n\r')
print(s2.strip(' \t\n\r')) # 去除字符串中头尾的空格
s3 = ' hello world*'
print(s3.strip('*')) # 指定参数后,会按照指定参数去除,空格失效
# 删除两边的特殊符号和空格
str1 = '-+-+-《黑神话:悟空》+--+- '
# 删除两边 - + 和空格
print(str1.strip().strip('-+'))
# 删除含有指定字符的所有字符
s4 = '八百标兵 八百标兵奔北坡,炮兵并排北边跑 炮兵怕把标兵碰,标兵怕碰炮兵炮'
print(s4.strip('百八炮兵'))
# 解析:
# 1.首先从头开始:第一个字符是"八",包含在"百八炮兵"中,删掉。
# 第二个字符是"百"包含在"百八炮兵"中,删掉。以此类推,一直到字符不包含在"百八炮兵"中,停止删除。
# 2.再从尾开始:第一个字符是"炮",包含在"百八炮兵"中,删除。第二个字符是"兵",包含在"百八炮兵"中,
# 删除。以此类推,直到字符不包含在"百八炮兵"中,停止删除。
s = '\t\r\na b c,d\ne\n\t'
print(s.strip())
print(s.strip('\t\n'))
print(s.strip('\t\ne\r'))
3.6 判断
3.6.1 startswith()方法——是否以指定的子字符串开头
startswith() 方法用于检索字符串是否以指定子字符串开头。如果是则返回 True,否则返回 False。startswith() 方法的语法格式如下:
In [16]: str.startswith?
Docstring:
S.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
Type: method_descriptor
参数说明:
1.S: 表示原字符串。
2.prefix: 表示要检索的子字符串。
3.start: 可选参数,表示检索范围的起始位置的索引,如果不指定,则从头开始检索。
4.end: 可选参数,表示检索范围的结束位置的索引,如果不指定,则一直检索到结尾。
示例代码:
s = "www.baidu.com"
print(s.startswith('ww')) # True
print(s.startswith('d', 7)) # True
print(s.startswith('d', 10)) # False
print(s.startswith('com', 11)) # False
print(s.startswith('')) # True
print(s.startswith(())) # False
# 判断手机号是否以"130"、"131"、"186"等联通手机号段开头
while 1:
# 创建元组
tuples = ('130', '131', '132', '155', '156', '175', '176', '185', '186', '166')
str1 = input('请输入联通手机号:')
# 判断手机号是否以指定的字符开头
# 如果传入的 prefix 是一个可迭代对象(如元组),则 startswith() 会检查字符串是否以该元组中的任意一个元素开头。
my_val = str1.startswith(tuples, 0) # ?还能这么用
if my_val:
print(str1.startswith(tuples, 0))
break
else:
print('您输入的不是联通手机号,请重新输入!')
# 分类数据筛选之筛选列车车次
# 列车车次数据
train = ['D74', 'D20', 'G240', 'D102', 'Z158', 'G394', 'K1304', 'D30',
'D22', 'G384', 'G382', 'D4606', 'K350', 'K340',
'Z62', 'Z64', 'K266', 'Z118']
f_letter = input('请输入车次首字母:')
for t in train:
if t.startswith(f_letter): # 判断车次是否以指定的字符开头
print(t)
3.6.2 endswith()方法——是否以指定子字符串结尾
endswith() 方法用于检索字符串是否以指定子字符串结尾。如果是则返回 True,否则返回 False。endswith() 方法的语法格式如下:
In [21]: str.endswith?
Docstring:
S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
Type: method_descriptor
参数说明:
1.S: 表示原字符串。
2.suffix: 表示要检索的子字符串。
3.start: 可选参数,表示检索范围的起始位置的索引,如果不指定,则从头开始检索。
4.end: 可选参数,表示检索范围的结束位置的索引,如果不指定,则一直检索到结尾。
ps:
1.如果传入的 suffix 是一个元组,endswith() 会检查字符串是否以元组中的任意一个元素作为后缀。
2.如果没有匹配的后缀,返回 False。
3.如果 suffix 传入一个空元组或空字符串(' ',而不是''),endswith() 会始终返回 False。
示例代码:
# 传入字符串作为后缀
text = "example.txt"
result = text.endswith(".txt")
print(result) # True
# 传入元组作为后缀集合
text = "example.txt"
result = text.endswith((".txt", ".doc", ".pdf"))
# 这里 endswith() 检查 text 是否以元组中的任意一个后缀结束。由于 text 以 ".txt" 结尾,所以返回 True。
print(result) # True
# 指定结束位置
text = "example.txt"
result = text.endswith("example", 0, 7)
print(result) # True
# 传入包含多个后缀的元组,指定范围
text = "document.pdf"
result = text.endswith((".txt", ".doc", ".pdf"), 0, 11)
print(result) # False
print(text.endswith(' ')) # False
print(text.endswith('')) # True
print(text.endswith(())) # False
3.6.3 isalnum()方法——判断字符串是否由字母和数字组成
isalnum() 方法用于判断字符串是否由字母和数字组成。isalnum() 方法的语法格式如下:
In [22]: str.isalnum?
Signature: str.isalnum(self, /)
Docstring:
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and
there is at least one character in the string.
Type: method_descriptor
如果字符串中至少有一个字符并且所有字符都是字母(a-z, A-Z)或数字(0-9)则返回True,否则返回False。
示例代码:
s1 = 'amo 123'
s2 = s1.replace(' ', '') # 滤除空格
r1 = s1.isalnum()
r2 = s2.isalnum()
print('原字符串:', s1)
print('滤除空格后:', s2)
print(r1) # False
print(r2) # True
3.6.4 isalpha()方法——判断字符串是否只由字母组成
isalpha() 方法用于判断字符串是否只由字母组成。isalpha() 方法的格式如下:
In [23]: str.isalpha?
Signature: str.isalpha(self, /)
Docstring:
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there
is at least one character in the string.
Type: method_descriptor
说明:
1.如果字符串中至少有一个字符并且所有字符都是字母则返回True,否则返回False
2.字母字符包括所有 Unicode 字母字符,因此支持多种语言的字符。
示例代码:
text = "HelloWorld"
result = text.isalpha()
print(result)
text = "Hello World"
result = text.isalpha()
print(result)
text = "Hello123"
result = text.isalpha()
print(result)
text = "Hello@World"
result = text.isalpha()
print(result)
text = "Привет"
result = text.isalpha()
print(result) # True isalpha() 支持所有语言的字母字符,因此即使是非拉丁字母的字符串,也能返回 True。
text = ""
result = text.isalpha()
print(result)
3.6.5 isdecimal()方法——判断字符串是否只包含十进制字符
isdecimal() 方法用于检查字符串是否只包含十进制字符。这种方法只适用于 unicode 对象。注意:定义一个十进制字符串,只要在字符串前添加 'u'
前缀即可。isdecimal() 方法的语法格式如下:
In [24]: str.isdecimal?
Signature: str.isdecimal(self, /)
Docstring:
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and
there is at least one character in the string.
Type: method_descriptor
如果字符串只包含数字则返回True,否则返回False。
示例代码:
text = "12345"
result = text.isdecimal()
print(result)
text = "123a45"
result = text.isdecimal()
print(result)
text = "123-45"
result = text.isdecimal()
print(result)
text = "12345" # 全角数字字符
result = text.isdecimal()
print(result)
text = "²³¼"
result = text.isdecimal()
print(result)
text = ""
result = text.isdecimal()
print(result)
"""
isdecimal() 仅对包含十进制数字字符的字符串返回 True,例如阿拉伯数字和全角数字字符。
它不会识别上标、下标、分数或罗马数字等作为十进制数字字符。
如果字符串为空,isdecimal() 始终返回 False。
"""
s1 = u'amo12468'
print(s1.isdecimal())
s2 = u'12468'
print(s2.isdecimal())
3.6.6 isdigit()方法——判断字符串是否只由数字组成
isdigit() 方法用于判断字符串是否只由数字组成。isdigit() 方法的语法格式如下:
In [25]: str.isdigit?
Signature: str.isdigit(self, /)
Docstring:
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there
is at least one character in the string.
Type: method_descriptor
如果字符串只包含数字则返回True,否则返回False
示例代码:
while True:
str1 = input('请输入数字:')
# 使用isdigit()方法判断是否为全数字
my_val = str1.isdigit()
if my_val:
strint = int(str1) # 将数字转换为整型
print(strint) # 输出
print(type(strint)) # 判断类型
break
else:
print('不是数字,请重新输入!')
3.6.7 isidentifier()方法——判断字符串是否为合法的Python标识符或变量名
isidentifier() 方法用于判断字符串是否是有效的 Python 标识符,还可以用来判断变量名是否合法。isidentifier() 方法的语法格式如下:
In [26]: str.isidentifier?
Signature: str.isidentifier(self, /)
Docstring:
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
such as "def" or "class".
Type: method_descriptor
如果字符串是有效的Python标识符返回True,否则返回False。
isidentifier() 仅检查字符串是否可以作为标识符使用,不会检查字符串是否为保留关键字
示例代码:
print('if'.isidentifier())
print('break'.isidentifier())
print('class'.isidentifier())
print('def'.isidentifier())
print('while'.isidentifier())
print('_b'.isidentifier())
print('云从科技888m'.isidentifier())
print('886'.isidentifier())
print('8a'.isidentifier())
print(''.isidentifier())
print('A2345@'.isidentifier())
3.6.8 islower()方法——判断字符串是否全由小写字母组成
islower() 方法用于判断字符串是否由小写字母组成。islower() 方法的语法格式如下:
In [27]: str.islower?
Signature: str.islower(self, /)
Docstring:
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and
there is at least one cased character in the string.
Type: method_descriptor
如果字符串中包含至少一个区分大小写的字符,并且所有这些字符都是小写,则返回True,否则返回False。
示例代码:
s1 = 'hello world'
print(s1.islower())
s2 = 'Hello World'
print(s2.islower())
3.6.9 isnumeric()方法——判断字符串是否只由数字(支持罗马数字、汉字数字等)组成
isnumeric() 方法用于判断字符串是否只由数字组成。这种方法是只针对 unicode 对象。注意:定义一个字符串为 Unicode,只要在字符串前添加 'u'
前缀即可。isnumeric() 方法的语法格式如下:
In [28]: str.isnumeric?
Signature: str.isnumeric(self, /)
Docstring:
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at
least one character in the string.
Type: method_descriptor
如果字符串只由数字组成,则返回True,否则返回False
示例代码:
s1 = u'amo12468' # 可以不用加u前缀 python3默认就是unicode编码
print(s1.isnumeric())
s1 = u'12468'
print(s1.isnumeric())
s1 = u'ⅠⅡⅣⅦⅨ'
print(s1.isnumeric())
s1 = u'㈠㈡㈣㈥㈧'
print(s1.isnumeric())
s1 = u'①②④⑥⑧'
print(s1.isnumeric())
s1 = u'⑴⑵⑷⑹⑻'
print(s1.isnumeric())
s1 = u'⒈⒉⒋⒍⒏'
print(s1.isnumeric())
s1 = u'壹贰肆陆捌uuu'
print(s1.isnumeric())
3.6.10 isprintable()方法——判断字符是否为可打印字符
isprintable() 方法用于判断字符串中所有字符是否都是可打印字符或字符串为空。Unicode 字符集中 Other
、Separator
类别的字符是不可打印的字符(但不包括 ASCII 码中的空格(0x20))。isprintable() 方法可用于判断转义字符。isprintable() 方法的语法格式如下:
In [29]: str.isprintable?
Signature: str.isprintable(self, /)
Docstring:
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in
repr() or if it is empty.
Type: method_descriptor
如果字符串中的所有字符都是可打印的字符或字符串为空则返回True,否则返回False
说明:ASCII 码中第 0~32
号及第 127
号是控制字符;第 33~126
号是可打印字符,其中第 48~57
号为 0~9
十个阿拉伯数字;65~90
号为26个大写英文字母,97~122
号为26个小写英文字母。示例代码:
s1 = '\n\t'
print(s1.isprintable())
s1 = 'amo_cx'
print(s1.isprintable())
s1 = '12345'
print(s1.isprintable())
s1 = '蜘蛛侠'
print(s1.isprintable())
3.6.11 isspace()方法——判断字符串是否只由空格组成
isspace() 方法用于判断字符串是否只由空格组成。isspace() 方法的语法格式如下:
In [30]: str.isspace?
Signature: str.isspace(self, /)
Docstring:
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there
is at least one character in the string.
Type: method_descriptor
如果字符串中只包含空格,则返回True,否则返回False
示例代码:
s1 = '\n \r\n \t \f'
print(s1.isspace())
s1 = 'amo xw 1996'
print(s1.isspace())
3.6.12 istitle()方法——判断首字母是否大写其他字母小写
istitle() 方法用于判断字符串中所有的单词首字母是否为大写而其他字母为小写。istitle() 方法的语法格式如下:
In [32]: str.istitle?
Signature: str.istitle(self, /)
Docstring:
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only
follow uncased characters and lowercase characters only cased ones.
Type: method_descriptor
如果字符串中所有的单词首字母为大写而其他字母为小写则返回True,否则返回False
istitle() 方法只检查字母部分是否符合标题样式,非字母字符(如标点符号、空格)不会影响结果
示例代码:
text = "This Is A Title"
result = text.istitle()
print(result)
text = "This is a Title"
result = text.istitle()
print(result)
text = "THIS IS A TITLE"
result = text.istitle()
print(result)
text = "this Is A Title"
result = text.istitle()
print(result)
text = "Hello, World!"
# 即使字符串中包含非字母字符,istitle() 仍然判断字母部分是否符合标题样式。
result = text.istitle()
print(result)
text = "Python"
result = text.istitle()
print(result)
3.6.13 isupper()方法——判断字符串是否全由大写字母组成
isupper() 方法用于判断字符串中所有的字母是否都是大写。isupper() 方法的语法格式如下:
In [33]: str.isupper?
Signature: str.isupper(self, /)
Docstring:
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and
there is at least one cased character in the string.
Type: method_descriptor
如果字符串中包含至少一个区分大小写的字符,并且所有这些字符都是大写,则返回True,否则返回False
isupper() 方法仅检查字母部分是否都是大写字母,非字母字符(如数字、符号、空格)不会影响结果。
示例代码:
# 全部字母大写的字符串
text = "HELLO WORLD"
result = text.isupper()
print(result) # 输出: True
# 包含小写字母的字符串
text = "Hello World"
result = text.isupper()
print(result) # 输出: False
# 包含数字的字符串
text = "123ABC"
result = text.isupper()
print(result) # 输出: True
# 包含非字母字符的字符串
text = "HELLO, WORLD!"
result = text.isupper()
print(result) # 输出: True
# 所有字母都是大写,但字符串包含空格
text = "HELLO WORLD"
result = text.isupper()
print(result) # 输出: True
# 包含小写字母和大写字母的混合
text = "HELLO world"
result = text.isupper()
print(result) # 输出: False
# 空字符串
text = ""
result = text.isupper()
print(result) # 输出: False
3.7 字符串转换方法(用的少)
3.7.1 capitalize()方法——字符串首字母转换为大写
capitalize() 方法用于将字符串的首字母转换为大写,其他字母为小写。capitalize() 方法的语法格式如下:
In [1]: str.capitalize?
Signature: str.capitalize(self, /)
Docstring:
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower
case.
Type: method_descriptor
示例代码:
# 1.将字符串的首字母转换为大写
str1 = 'hello word!'
print(str1)
print(str1.capitalize()) # Hello word!
# 2.字符串全是大写字母只保留首字母大写
cn = '没什么是你能做却办不到的事。'
en = "THERE'S NOTHING YOU CAN DO THAT CAN'T BE DONE."
print(cn)
print('原字符串:', en)
# 字符串转换为小写后首字母大写
print('转换后:', en.lower().capitalize())
print('转换后:', en.capitalize()) # 效果是一样的
# 对指定位置字符串转换为首字母大写
print(en[0:16] + en[16:].capitalize())
3.7.2 casefold()方法——所有大写字符转换为小写
casefold() 方法是 Python3.3 版本之后引入的,其效果和 lower() 方法非常相似,都可以转换字符串中所有大写字符为小写。两者的区别是:lower() 方法只对 ASCII 编码,也就是 A-Z
有效,而 casefold() 方法对所有大写(包括非中英文的其他语言)都可以转换为小写。casefold() 方法的语法格式如下:
In [2]: str.casefold?
Signature: str.casefold(self, /)
Docstring: Return a version of the string suitable for caseless comparisons.
Type: method_descriptor
说明: 返回将字符串中所有大写字符转换为小写后生成的字符串
示例代码:
# 1.将字符串中的大写字母转换为小写
str1 = 'HELLO WORLD'
str2 = 'Hello World'
print(str1.casefold()) # hello world
print(str2.casefold()) # hello world
# 2.对非中英文的其他语言字符串中的大写转换为小写
a = 'ß Fußball' # 德语
print(a.lower())
print(a.casefold())
3.7.3 lower()方法——大写字母转换为小写字母
lower() 方法用于将字符串中的大写字母转换为小写字母。如果字符串中没有需要被转换的字符,则将原字符串返回;否则将返回一个新的字符串,将原字符串中每个需要进行小写转换的字符都转换成等价的小写字符,且字符长度与原字符长度相同,例如下图所示的效果:
lower() 方法的语法格式如下:
In [3]: str.lower?
Signature: str.lower(self, /)
Docstring: Return a copy of the string converted to lowercase.
Type: method_descriptor
说明: 其中,str为要进行转换的字符串
示例代码:
# 1.将字符串中的大写字母转换为小写字母
str1 = 'Hello World'
print(str1.lower()) # 全部转换为小写字母输出
# 2.将大驼峰值改为小驼峰值
s1 = 'StudentName'
s2 = 'StudentCount'
print(s1[:1].lower() + s1[1:]) # studentName
print(s2[:1].lower() + s2[1:]) # studentCount
3.7.4 swapcase()方法——大小写字母互转
swapcase() 方法用于对字符串的大小写字母进行转换并生成新的字符串,原字符串中的字母大写使用 swapcase() 方法后会转成小写;原字符串中的字母小写使用 swapcase() 方法后会转成大写。swapcase() 方法的语法格式如下:
In [4]: str.swapcase?
Signature: str.swapcase(self, /)
Docstring: Convert uppercase characters to lowercase and lowercase characters to uppercase.
Type: method_descriptor
示例代码:
s1 = 'Hello World'
s2 = 'HELLO'
s3 = 'hello'
s4 = 'hello-World'
print(s1.swapcase()) # hELLO wORLD
print(s2.swapcase()) # hello
print(s3.swapcase()) # HELLO
print(s4.swapcase()) # HELLO-wORLD
3.7.5 title()方法——单词首字母转换为大写
title() 方法与前面介绍的 capitalize() 有些区别,该方法用于将字符串中的每个单词的首字母转换为大写字母,其余字母均为小写,例如下图所示的效果:
title() 方法的语法格式如下:
In [5]: str.title?
Signature: str.title(self, /)
Docstring:
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining
cased characters have lower case.
Type: method_descriptor
示例:
# 将字符串中每个单词的首字母转换为大写
str1 = "hello word!"
print(str1.title()) # Hello Word!
3.7.6 upper()方法——字符串小写字母转换为大写字母
upper() 方法用于将字符串中的小写字母转换为大写字母。如果字符串中没有需要被转换的字符,则将原字符串返回;否则返回一个新字符串,将原字符串中每个需要进行大写转换的字符都转换成等价的大写字符,且新字符长度与原字符长度相同,例如下图所示的效果:
upper() 方法的语法格式如下:
In [6]: str.upper?
Signature: str.upper(self, /)
Docstring: Return a copy of the string converted to uppercase.
Type: method_descriptor
说明: 其中,str为要进行转换的字符串
示例代码:
str1 = 'www.BAIDU.com'
print(str1.upper()) # 全部转换为大写字母输出 WWW.BAIDU.COM
3.7.7 maketrans()方法——创建字符映射的转换表
maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。两个字符串的长度必须相同,为一一对应的关系。maketrans() 方法的语法格式如下:
In [7]: str.maketrans?
Docstring:
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode
ordinals (integers) or characters to Unicode ordinals, strings or None.
Character keys will be then converted to ordinals.
If there are two arguments, they must be strings of equal length, and
in the resulting dictionary, each character in x will be mapped to the
character at the same position in y. If there is a third argument, it
must be a string, whose characters will be mapped to None in the result.
Type: builtin_function_or_method
说明:
1.str.maketrans(x[, y[, z]])
2.参数
x: 可以是一个字典,也可以是一个字符串。
如果 x 是一个字典,则字典的键表示要替换的字符,值表示要替换成的字符。
如果 x 是一个字符串,则 y 也必须是一个字符串,并且它们的长度必须相同。x 中的字符将被替换为 y 中的对应字符。
y: (可选)一个字符串,它与 x 一一对应,用于替换 x 中的字符。
z: (可选)一个字符串,表示需要删除的字符。
3.返回值
返回一个转换表,这个表可以传递给 translate() 方法来实现字符替换或删除。
示例代码:
# 1.将字符串中的字符替换为其他字符
# 使用两个字符串创建映射表
in_tab = "aeiou"
out_tab = "12345"
text = "hello world"
# trans_table = str.maketrans(in_tab, out_tab)
# result = text.translate(trans_table)
# print(result) # 输出: h2ll4 w4rld
# 也可以
my_str = text.maketrans(in_tab, out_tab)
print(text.translate(my_str)) # 输出: h2ll4 w4rld
# 2.删除字符串中的特定字符:
in_tab = "aeiou"
trans_table = str.maketrans("", "", in_tab)
text = "hello world"
result = text.translate(trans_table)
print(result) # 输出: hll wrld
# 3.使用字典创建映射表
trans_table = str.maketrans({"a": "1", "e": "2", "i": "3", "o": "4", "u": "5"})
text = "hello world"
result = text.translate(trans_table)
print(result) # 输出: h2ll4 w4rld
# 4.结合替换和删除
# 替换字符并删除指定字符
in_tab = "aeiou"
out_tab = "12345"
delete_chars = "ld"
trans_table = str.maketrans(in_tab, out_tab, delete_chars)
text = "hello world"
result = text.translate(trans_table)
print(result) # 输出: h24 w4r
3.7.8 translate()方法——按照转换表转换字符
translate() 方法用于根据给定的字符映射转换表替换字符串中的字符。通常,这个转换表由 str.maketrans() 方法创建。translate() 方法的语法如下:
In [8]: str.translate?
Signature: str.translate(self, table, /)
Docstring:
Replace each character in the string using the given translation table.
table
Translation table, which must be a mapping of Unicode ordinals to
Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a
dictionary or list. If this operation raises LookupError, the character is
left untouched. Characters mapped to None are deleted.
Type: method_descriptor
参数说明:
1.table:转换表,它是通过maketrans方法转换而来的。
2.返回值:返回转换后的新字符串。
说明:translate()方法一般与maketrans()方法配合使用,这里不再赘述。有关translate()方法的应用可参考maketrans()方法。
示例代码:
# 去掉文本中拼音的音调
import sys
import unicodedata # unicodedata: 用于处理 Unicode 字符,比如对字符的规范化和组合型字符的处理。
my_str = 'Jí Lín Shěng Míng Rì Kē Jì Yǒu Xiàn Gōng Sī'
# 将unicode字符串转换为普通格式的字符
# 将字符串规范化为分解形式 (NFD),将带有音调的字符分解为基础字符和组合字符(如音调)。
# 例如,'í' 会被分解为 'i' 和组合字符 '´'。
b = unicodedata.normalize('NFD', my_str)
# 列出组合型字符,并使用dict.fromkeys()方法构造一个字典
# sys: 用于获取 Python 解释器的最大 Unicode 编码值。
# 使用生成器表达式构建一个字典,该字典的键是所有组合字符(如音调),值为 None。
# fromkeys() 方法用于创建一个字典,键为所有 Unicode 组合字符。
my_chr = dict.fromkeys(c for c in range(sys.maxunicode) if unicodedata.combining(chr(c)))
# 去除音调
print(b.translate(my_chr)) # Ji Lin Sheng Ming Ri Ke Ji You Xian Gong Si
3.8 字符对齐方法(用的少)
3.8.1 center()方法——字符串居中填充
字符串对象的 center() 方法用于将字符串填充至指定长度,并将原字符串居中输出。center() 方法的语法格式如下:
In [9]: str.center?
Signature: str.center(self, width, fillchar=' ', /)
Docstring:
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
Type: method_descriptor
参数说明:
1.width参数表示要扩充的长度,即新字符串的总长度。
2.fillchar参数表示要填充的字符,如果不指定该参数,则使用空格字符来填充。
示例代码:
# 填充指定的字符串
s1 = '云从科技'
print(s1.center(10)) # 长度为10,不指定填充字符,前后各填充3个空格
print(s1.center(6, '-')) # 长度为6,指定填充字符,前后各填充一个'-'字符
print(s1.center(5, '-')) # 长度为5,只在字符串前填充一个'-'字符
print(s1.center(12, '-')) # 长度为12,字符串前后各填充4个'-'字符
print(s1.center(3, '-')) # 长度为3,不足原字符串长度,输出原字符串
# 文本按照顺序显示并且居中对齐
s_list = ['锦瑟',
'李商隐',
'锦瑟无端五十弦',
'一弦一柱思华年',
'庄生晓梦迷蝴蝶',
'望帝春心托杜鹃',
'沧海月明珠有泪',
'蓝田日暖玉生烟',
'此情可待成追忆',
'只是当时已惘然']
for s in s_list:
print('||%s||' % s.center(11, ' '))
3.8.2 ljust()方法——字符串左对齐填充
字符串对象的 ljust 方法是用于将字符串进行左对齐右侧填充。ljust() 方法的语法格式如下:
In [10]: str.ljust?
Signature: str.ljust(self, width, fillchar=' ', /)
Docstring:
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
Type: method_descriptor
参数说明:
1.width参数表示要扩充的长度,即新字符串的总长度。
2.fillchar参数表示要填充的字符,如果不指定该参数,则使用空格字符来填充。
示例代码:
# 1.左对齐填充指定的字符串
s1 = '云从科技'
print(s1.ljust(8)) # 长度为8,不指定填充字符,字符串后由4个空格字符来填充
print(s1.ljust(5, "-")) # 长度为5,指定填充字符,字符串后填充一个"-"字符
print(s1.ljust(3, "-")) # 长度为3,不足原字符串长度,输出原字符串
# 2.中英文混排对齐
ulist = list()
ulist.append([1, '北京大学', 'Peking University', '685'])
ulist.append([2, '中国人民大学', 'Renmin University of China', '685'])
ulist.append([3, '浙江大学', 'Zhejiang University', '676'])
ulist.append([4, '武汉大学', 'Wuhan University', '632'])
ulist.append([5, 'mrsoft', 'mrsoft', '123'])
ulist.append([6, 'mr学院', 'mr College', '123'])
for ul in ulist:
len1 = len(ul[1].encode('gbk')) - len(ul[1]) # 更改编码方式后计算字符串长度
# 使用ljust()和rjust()方法对齐
print(ul[0], ul[1].ljust(20 - len1), ul[2], ul[3].rjust(30 - len(ul[2])))
3.8.3 rjust()方法——字符串右对齐填充
字符串对象的 rjust 方法是用于将字符串进行右对齐左侧填充。rjust() 方法的语法格式如下:
In [11]: str.rjust?
Signature: str.rjust(self, width, fillchar=' ', /)
Docstring:
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
Type: method_descriptor
参数说明:
1.width:表示要扩充的长度,即新字符串的总长度。
2.fillchar:表示要填充的字符,如果不指定该参数,则使用空格字符来填充。
示例代码:
s1 = '云从科技'
print(s1.rjust(8)) # 长度为8,不指定填充字符,字符串前由4个空格字符来填充
print(s1.rjust(5, "-")) # 长度为5,指定填充字符,字符串前填充一个"-"字符
print(s1.rjust(3, "-")) # 长度为3,不足原字符串长度,输出原字符串
四、编码与解码
字符编码可以参考文章 https://blog.csdn.net/xw1680/article/details/134001443 中 八、字符编码
一节学习。
转义字符可以参考文章:https://blog.csdn.net/xw1680/article/details/134027522 中的 二、在C语言中使用英文字符
一节中的 2.3 字符与整数
与 2.4 C语言转义字符
进行学习。
4.1 字节串
在 Python 中,有两种常用的字符串类型,分别为 str 和 bytes。其中, str 表示 Unicode 字符(ASCII
或者其他),bytes 表示二进制数据(包括编码的文本)。这两种类型的字符串不能拼接在一起使用。通常情况下,str 在内存中以 Unicode 表示,一个字符对应若干个字节。但是如果在网络上传输,或者存到磁盘上,就需要把 str 转换为字节类型,即 bytes 类型。
字节串(bytes)也称字节序列,是不可变的序列,存储以字节为单位的数据。提示:bytes 类型是 Python3 新增的一种数据类型。字节串与字符串的比较:
- 字符串是由多个字符构成,以字符为单位进行操作。默认为 Unicode 字符,字符范围为 0~65535。字符串是字符序列,它是一种抽象的概念,不能直接存储在硬盘,用以显示供人阅读或操作。
- 字节串是由多个字节构成,以字节为单位进行操作。字节是整型值,取值范围 0~255。字节串是字节序列,因此可以直接存储在硬盘。
除了操作单元不同外,字节串与字符串的用法基本相同。它们之间的映射被称为解码或编码。定义字节串的方法如下:
(1) 使用字面值:以 b 操作符为前缀的 ASCII 字符串。语法格式如下:
b"ASCII 字符串"
b"转义序列"
字节是 0~255 之间的整数,而 ASCII 字符集范围为 0~255,因此它们之间可以直接映射。通过转义序列可以映射更大规模的字符集。使用字面值直接定义字节串,如下:
# 创建空字节串的字面值
byte1 = b''
byte2 = b""
byte3 = b''''''
byte4 = b""""""
# 创建非空字节串的字面值
byte5 = b'ABCD'
byte6 = b'\x41\x42'
print(byte1)
print(byte6)
(2) 使用 bytes() 函数:使用 bytes() 函数可以创建一个字节串对象,简明语法格式如下:
In [14]: bytes?
Init signature: bytes(self, /, *args, **kwargs)
Docstring:
bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object
Construct an immutable array of bytes from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- any object implementing the buffer API.
- an integer
Type: type
Subclasses:
bytes() # 生成一个空的字节串,等同于b''
bytes(整型可迭代对象) # 用可迭代对象初始化一个字节串,元素必须为[0,255]中的整数
bytes(整数n) # 生成n个值为零的字节串
bytes('字符串', encoding='编码类型') # 使用字符串的转换编码生成一个字节串
下面示例使用 bytes()
函数创建多个字节串对象:
a = bytes() # 等效于b''
b = bytes([10, 20, 30, 65, 66, 67]) # 等效于b'\n\x14\x1eABC'
print(b)
c = bytes(range(65, 65 + 26))
print(c) # b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
d = bytes(5)
print(d) # b'\x00\x00\x00\x00\x00'
e = bytes('hello 中国', 'utf-8')
print(e) # b'hello \xe4\xb8\xad\xe5\x9b\xbd'
# 简单操作
print(b'abcd'[2]) # 返回int,指定是本字节对应的十进制数 99
x = b'\t\x09'
print(x, len(x)) # b'\t\t' 2
y = br'\t\x09'
print(y, len(y)) # b'\\t\\x09' 6
字节串是不可变序列,使用 bytearray() 可以创建可变的字节序列,也称为字节数组(bytearray)。数组是每个元素类型完全相同的一组列表,因此可以使用操作列表的方法来操作数组。bytearray() 函数的简明语法格式如下:
In [15]: bytearray?
Init signature: bytearray(self, /, *args, **kwargs)
Docstring:
bytearray(iterable_of_ints) -> bytearray
bytearray(string, encoding[, errors]) -> bytearray
bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
bytearray() -> empty bytes array
Construct a mutable bytearray object from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- a bytes or a buffer object
- any object implementing the buffer API.
- an integer
Type: type
Subclasses:
bytearray() # 生成一个空的可变字节串,等同于 bytearray(b'')
bytearray(整型可迭代对象) # 用可迭代对象初始化一个可变字节串,元素必须为 [0, 255] 中的整数
bytearray(整数n) # 生成 n 个值为零的可变字节串
bytearray(字符串, encoding='utf-8') # 用字符串的转换编码生成一个可变字节串
示例代码:
# 1. 从字符串创建 bytearray
text = "Hello, World!"
ba1 = bytearray(text, 'utf-8')
print(ba1) # 输出: bytearray(b'Hello, World!')
# 2. 从整数创建 bytearray
size = 5
ba2 = bytearray(size)
print(ba2) # 输出: bytearray(b'\x00\x00\x00\x00\x00')
# 3. 从可迭代对象创建 bytearray
data = [65, 66, 67, 68]
ba3 = bytearray(data)
print(ba3) # 输出: bytearray(b'ABCD')
# 4. 从字节序列创建 bytearray
b = b"Hello, World!"
ba4 = bytearray(b)
print(ba4) # 输出: bytearray(b'Hello, World!')
# 5. 修改 bytearray 对象
ba5 = bytearray(b"Hello, World!")
ba5[0] = 74 # 将第一个字节修改为 'J'
print(ba5) # 输出: bytearray(b'Jello, World!')
print(ba5[0]) # 74
# 6. bytearray 对象的切片
ba6 = bytearray(b"Hello, World!")
print(ba6[:5]) # 输出: bytearray(b'Hello')
# 7. 附加字节到 bytearray
ba7 = bytearray(b"Hello")
ba7.append(33) # 添加 '!' (ASCII 33)
print(ba7) # 输出: bytearray(b'Hello!')
# 8. 转换回 bytes 或 str
ba8 = bytearray(b"Hello, World!")
b = bytes(ba8)
print(b) # 输出: b'Hello, World!'
s = ba8.decode('utf-8')
print(s) # 输出: Hello, World!
b = bytearray()
"""
append(int) 尾部追加一个元素
insert(index, int) 在指定索引位置插入元素
extend(iterable_of_ints)将一个可迭代的整数集合追加到当前bytearray pop(index=-1)从指定索引上移除元素,默认从尾部移除
remove(value) 找到第一个value移除,找不到抛ValueError异常
注意:上述方法若需要使用int类型,值在[0, 255]
clear() 清空bytearray
reverse() 翻转bytearray,就地修改
"""
b.append(97)
b.append(99)
b.insert(1, 98)
b.extend([65, 66, 67])
print(b) # bytearray(b'abcABC')
b.remove(66)
b.pop()
b.reverse()
print(b) # 输出什么 bytearray(b'Acba')
b.clear()
print(b) # bytearray(b'')
4.2 编码与解码
4.2.1 encode() 方法——编码字符串
编码是将文本(字符串)转换成字节流,Unicode 格式转换成其他编码格式。在 Python 中提供了 encode() 方法,该方法的作用是将 Unicode 编码转换成其他编码的字符串,如下图所示。如 str1.encode('gbk')
,表示将 Unicode 编码的字符串 str1 转换成 GBK 编码。
encode() 方法的语法格式如下:
In [16]: str.encode?
Signature: str.encode(self, /, encoding='utf-8', errors='strict')
Docstring:
Encode the string using the codec registered for encoding.
encoding
The encoding in which to encode the string.
errors
The error handling scheme to use for encoding errors.
The default is 'strict' meaning that encoding errors raise a
UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that can handle UnicodeEncodeErrors.
Type: method_descriptor
参数说明:
- str:表示要进行转换的字符串。
encoding="utf-8"
:可选参数,用于指定进行转码时采用的编码,默认为 utf-8,如果想使用简体中文可以设置为 gbk 或 gb2312(与网站使用的编码方式有关)。当只有一个参数时,可省略前面的encoding=
,直接写编码。errors="strict"
:可选参数,用于指定错误处理方式,其可选择值可以是 strict(遇到非法字符就抛出异常)、ignore(忽略非法字符)、replace(用"?"
替换非法字符)或 xmlcharrefreplace(使用 XML 的字符引用)等,默认值为 strict。
【示例1】将指定字符串转为不同的编码格式。
test_str = '我爱Amo' # 定义字符串
utf8Str = test_str.encode(encoding='utf-8') # 采用utf-8编码
gbkStr = test_str.encode(encoding='gbk') # 采用GBK编码
print(utf8Str) # 输出utf-8编码内容:b'\xe6\x88\x91\xe7\x88\xb1Amo'
print(gbkStr) # 输出GBK编码内容:b'\xce\xd2\xb0\xaeAmo'
【示例2】Python中URL链接的编码处理。
最近在豆瓣电影搜索《千与千寻》的时候发现搜素链接是这样的:
https://movie.douban.com/subject_search?search_text=%E5%8D%83%E4%B8%8E%E5%8D%83%E5%AF%BB&cat=1002
很明显 千与千寻
被编码成了 %E5%8D%83%E4%B8%8E%E5%8D%83%E5%AF%BB,那么在 Python 中如何处理这种链接呢?首先来了解下 URL 编码方法:URL 编码方式是把需要编码的字符转化为 %xx
的形式。通常 URL 编码是基于 utf-8,也可能是 gbk 或 gb2312(这与网站使用的编码方式有关)。测试下上述链接中 URL 编码是否为 千与千寻
,首先使用 encode() 方法将 千与千寻
的编码格式设置为 utf-8,然后使用 urllib 模块的 quote() 函数将转码后的字符串设置为 URL 编码,代码如下:
from urllib.parse import quote
from urllib.parse import unquote
# 编码测试
my_str1 = '千与千寻'.encode('utf-8')
# 使用urllib模块quote函数进行编码
my_str2 = quote(my_str1)
print(my_str2) # %E5%8D%83%E4%B8%8E%E5%8D%83%E5%AF%BB
# 使用urllib模块unquote函数进行解码
print(unquote(my_str2))
将结果与链接中的字符串对比完全一样,那么这种编码方式可以通过 urllib 模块的 unquote 函数进行解码。
【示例3】将字节类型的HTML代码写入文件。
# 字节类型的html代码
html_bytes = bytes(
b'<html>'
b'<head>'
b'<title>Python\xe7\xbc\x96\xe7\xa8\x8b\xe8\xaf\xad\xe8\xa8\x80</title>'
b'</head>'
b'<body>'
b'<p>\xe4\xba\xba\xe7\x94\x9f\xe8\x8b\xa6\xe7\x9f\xad\xef\xbc\x8c\xe6\x88\x91\xe7\x94\xa8Python</p>'
b'</body>'
b'</html>')
# 以'w'模式进行写入
with open('html_bytes' + ".html", "w") as f:
# 将字节类型的html代码解码后写入文件中
f.write(html_bytes.decode('utf-8'))
4.2.2 decode() 方法——解码字符串
解码是将字节流转换成字符串(文本),其他编码格式转成 unicode。在 Python 中提供了 decode() 方法,该方法的作用是将其他编码的字符串转换成 unicode 编码,如 str1.decode('gb2312')
,表示将 gb2312 编码的字符串 str1 转换成 unicode 编码。decode() 方法的语法格式如下:
In [17]: bytes.decode?
Signature: bytes.decode(self, /, encoding='utf-8', errors='strict')
Docstring:
Decode the bytes using the codec registered for encoding.
encoding
The encoding with which to decode the bytes.
errors
The error handling scheme to use for the handling of decoding errors.
The default is 'strict' meaning that decoding errors raise a
UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
as well as any other name registered with codecs.register_error that
can handle UnicodeDecodeErrors.
Type: method_descriptor
参数说明:
- bytes:表示要进行转换的字节数据,通常是 encode() 方法转换的结果。
encoding="utf-8"
:可选参数,用于指定进行解码时采用的字符编码,默认为 utf-8,如果想使用简体中文可以设置为 gbk 或 gb2312(与网站使用的编码方式有关)。当只有一个参数时,可省略前面的encoding=
,直接写编码。errors="strict"
:可选参数,用于指定错误处理方式,其可选择值可以是 strict(遇到非法字符就抛出异常)、ignore(忽略非法字符)、replace(用?
替换非法字符)或 xmlcharrefreplace(使用 XML 的字符引用)等,默认值为 strict。
【示例1】对指定的字符串进行解码。
# 定义字节编码
Bytes1 = bytes(b'\xe6\x88\x91\xe7\x88\xb1Amo')
# 定义字节编码
Bytes2 = bytes(b'\xce\xd2\xb0\xaeAmo')
str1 = Bytes1.decode("utf-8") # 进行utf-8解码
str2 = Bytes2.decode("gbk") # 进行gbk解码
print(str1) # 输出utf-8解码后的内容:我爱Amo
print(str2) # 输出gbk解码后的内容:我爱Amo
u = "中文"
str1 = u.encode("gb2312")
print(str1) # b'\xd6\xd0\xce\xc4'
str2 = u.encode("gbk")
print(str2) # b'\xd6\xd0\xce\xc4'
str3 = u.encode("utf-8")
print(str3) # b'\xe4\xb8\xad\xe6\x96\x87'
u = "中文"
str1 = u.encode("gb2312")
u1 = str1.decode("gb2312")
print(u1) # 输出:中文
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd6 in position 0: invalid continuation byte
u2 = str1.decode("utf-8") # 报错,因为str1是gb2312编码的
【示例2】解码爬虫获取的字节形式代码。在使用python爬取指定的网页时,获取的内容中,如果汉字都是字节码的情况下,可以通过 decode() 方法实现 html 代码的解码工作。代码如下:
import requests # 网络请求模块
# 对爬取目标发送网络请求
response = requests.get('https://www.baidu.com/')
html_bytes = response.content # 获取爬取的内容,该内容为字节形式
print(html_bytes) # 打印字节形式的html代码
print(html_bytes.decode('utf-8')) # 打印解码后的html代码
五、切片
线性结构特征:
- 可迭代 for … in
- 有长度,通过len(x)获取,容器
- 通过整数下标可以访问元素。正索引、负索引,可以切片。
已经学习过的线性结构:list、tuple、str、bytes、bytearray。语法格式:
sequence[start:stop]
sequence[start:stop:step]
# 通过给定的索引区间获得线性结构的一部分数据
# 参数说明:
# 1.start、stop、step为整数,可以是正整数、负整数、零
# 2.切片的起始位置(包含)。默认为序列的第一个元素索引,即0。为0时可以省略
# 3.切片的结束位置(不包含)。默认为序列的结束,即len(sequence)。为末尾时,可以省略
# 4.切片的步长。默认为 1,表示逐个元素切片。为1时,可以省略
# 5.切片时,索引超过上界(右边界),就取到末尾;超过下界(左边界),取到开头
# 6.ps: 切片不会改变原有的数据类型
在序列上使用切片[start:stop],子区间索引范围[start, stop),相当于从start开始指向stop的方向上获取数据
1.默认step为1,表示向右;步长为负数,表示向左
2.如果子区间方向和步长方向不一致,直接返回当前类型的"空对象"
3.如果子区间方向和步长方向一致,则从起点间隔步长取值
示例:
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x[:]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x[:-1]) # [0, 1, 2, 3, 4, 5, 6, 7, 8]
print(x[0:]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x[3:]) # [3, 4, 5, 6, 7, 8, 9]
print(x[3:-1]) # [3, 4, 5, 6, 7, 8]
print(x[9:]) # [9]
print(x[:9]) # [0, 1, 2, 3, 4, 5, 6, 7, 8]
print(x[9:-1]) # []
print(x[:100]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x[-100:]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x[4:-2]) # [4, 5, 6, 7]
print(x[-4:-2]) # [6, 7]
print('0123456789'[-4:8]) # '67'
print(b'0123456789'[-4:8]) # # b'67'
print(bytearray(b'0123456789')[-10:5]) # bytearray(b'01234')
print('------------------------------------------------------')
# 步长
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x[::]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x[::2]) # [0, 2, 4, 6, 8]
print(x[2:8:3]) # [2, 5]
print(x[:9:3]) # [0, 3, 6]
print(x[1::3]) # [1, 4, 7]
print(x[-10:8:2]) # [0, 2, 4, 6]
print('------------------------------------------------------')
# 起止和方向
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x[-10:]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x[-5:6]) # [5]
print(x[-5:-6]) # []
print(x[6:5]) # []
print(x[5:5]) # []
print(x[1:9:-2]) # []
print(x[::-2]) # [9, 7, 5, 3, 1]
print(x[8::-2]) # 表示索引8到左尽头,包含0 [8, 6, 4, 2, 0]
print(x[8:0:-2]) # 表示索引8到索引0,但不含0 [8, 6, 4, 2]
print(x[8:-10:2]) # []
print(x[8:-10:-2]) # [8, 6, 4, 2]
print(x[-5:4:-1]) # [5]
print(x[-5:5:-1]) # []
其他示例:
x = [0, 1, 2]
y = x[:]
print(x, y) # [0, 1, 2] [0, 1, 2]
print(id(x), id(y)) # 2468381458176 2468378390912
print(x is y) # False
print(x == y) # True
x[0] = 100
print(x, y) # [100, 1, 2] [0, 1, 2]
x = [[1]]
y = x[:]
print(x, y) # [[1]] [[1]]
print(x == y) # True
print(id(x), id(y), x is y) # False
x[0][0] = 100
print(x, y) # [[100]] [[100]]
print(x == y) # True
print(x is y) # False
x[0] = 200
print(x == y) # False
print(x, y) # [200] [[100]]
六、格式化字符串
6.1 使用百分号“%”格式化字符串(在Python源码中会经常看到和后续日志模块中也会使用到所以也需要掌握)
参考文章 https://blog.csdn.net/xw1680/article/details/136889807 中 十、Python格式化字符串(格式化输出)
中的 10.1 %运算符
小节。
6.2 format()函数与str.format()方法——格式化字符串
参考文章 https://blog.csdn.net/xw1680/article/details/136889807 中 十、Python格式化字符串(格式化输出)
中的 10.2 str.format()方法
与 10.3 format() 函数
小节。
6.3 f-string——格式化字符串
f-string 是格式化字符串的常量,它是 Python3.6 新引入的一种字符串格式化方法,主要目的是使格式化字符串的操作更加简便。f-string 在形式上是以 f 或 F 字母开头的字符串,然后通过一对单引号将要拼接的变量按顺序排列在一起,每个变量名称都需要使用一对花括号括起来,例如输出 IP 地址格式的字符串,如下图所示:
f-string 语法格式如下:
sval = f'{s1}{s2}{s3}……'
f-string 功能非常强大,而且使用起来也简单方便,因此 Python3.6 以上版本推荐使用 f-string 进行字符串格式化。下面详细介绍一下 f-string 在各个方面的应用。
示例代码:
# 1.连接指定字符串
s1 = '爵士'
s2 = ' vs '
s3 = '马刺'
print(f'{s1}{s2}{s3}')
# 2.替换指定内容
name = 'amo'
print(f'我的姓名是: {name}')
age = 18
print(f'我的年龄时: {age}')
city = '重庆市'
print(f'我在哪个城市: {city}')
# 3.表达式求值与函数调用
print(f'结果为: {1024 * 7688 + 8}')
name = 'AMO'
print(f'转换为小写: {name.lower()}')
print(f'结果为: {(2 + 5j) / (2 - 2j)}')
将数字格式化为二进制、八进制、十进制和十六进制。使用 f-string 可以实现将数字格式化为不同的进制数,省去了进制转换的麻烦,具体介绍如下:
- b:二进制整数格式
- d:十进制整数格式
- o:八进制整数格式
- x:十六进制整数格式(小写字母)
- X:十六进制整数格式(大写字母)
例如,将 12345 分别格式化为二进制、十进制、八进制和十六进制,代码如下:
a = 12345
print(f'二进制:{a:^#10b}') # 居中,宽度10位,二进制整数,显示前缀0b
print(f'十进制:{a:^#10d}') # 十进制整数
print(f'八进制:{a:^#10o}') # 八进制整数,显示前缀0o
print(f'十六进制:{a:^#10X}') # 十六进制整数(大写字母),显示前缀0X
字符串左对齐、右对齐和居中。f-string 支持三种对齐方式:
- <:左对齐(字符串默认对齐方式);
- >:右对齐(数值默认对齐方式);
- ^:居中。
下面以以左对齐、右对齐和居中输出 听天色等烟雨而我在等你
,固定宽度 18 位,代码如下:
a = '听天色等烟雨而我在等你'
print(f'左对齐:{a:<18}') # 左对齐
print(f'右对齐:{a:>18}') # 右对齐
print(f'居中对齐:{a:^18}') # 居中对齐
为数字添加千位分隔符。在数字中加进一个符号,可以避免因数字位数太多而难以看出它的值。一般每隔三位数加进一个逗号,也就是千位分隔符,以便更加容易认出数值。在 Python 中也可以实现这样的分隔符。下面使用 f-string 实现为数字加千位分隔符。f-string 可以使用 逗号(,)
和 下划线(_)
作为千位分隔符,其中 逗号(,)
仅适用于浮点数、复数与十进制整数,而对于浮点数和复数,逗号(,)
只分隔小数点前的数位;下划线(_)
适用于浮点数、复数和二进制、八进制、十进制和十六进制整数,对于浮点数和复数,下划线(_)
只分隔小数点前的数位,而对于二进制、八进制、十六进制整数,固定从低位到高位每隔四位插入一个 下划线(_)
,对于十进制整数则是每隔三位插入一个 下划线(_)
。下面举例说明,示例代码如下:
val1 = 123456.78
print(f'{val1:,}') # 浮点数使用,作为千位分隔符
val2 = 12345678
print(f'{val2:015,d}') # 高位补零,宽度15位,十进制整数,使用,作为千位分隔符
val3 = 0.5 + 2.5j
print(f'{val3:30.3e}') # 宽度30位,科学计数法,3位小数
val4 = 12345678988
print(f'{val4:_o}') # 八进制整数,使用_作为千位分隔符
在 f-string 大括号内填入 lambda 表达式。f-string 大括号内也可填入 lambda 表达式,但 lambda 表达式的 冒号(:)
会被 f-string 误认为是表达式与格式描述符之间的分隔符,为避免歧义,需要将 lambda 表达式置于 括号()
内,例如下面的代码:
# 结果为:16777217
print(f'结果为:{(lambda x: x ** 8 + 1)(8)}')
# 结果为:+257.0
print(f'结果为:{(lambda x: x ** 8 + 1)(2):<+8.1f}')
将系统日期格式化为短日期。f-string 可以对日期进行格式化,如格式化成类似系统中的短日期、长日期等,其适用于 date、datetime 和 time 对象,相关介绍如下:
- %d:表示日,是数字,以 0 补足两位
- %b:表示月(缩写)
- %B:表示月(全名)
- %m:表示月(数字,以 0 补足两位)
- %y:年(后两位数字,以 0 补足两位)
- %Y:年(完整数字,不补零)
下面输出当前系统日期并将其格式化为短日期格式,示例代码如下:
import datetime
e = datetime.datetime.today() # 获取当期系统日期
print('当前系统日期:', e) # 当前系统日期: 2024-08-27 07:14:59.509755
print(f'短日期格式:{e:%Y/%m/%d}') # 短日期格式:2024/08/27
print(f'短日期格式:{e:%Y-%m-%d}') # 短日期格式:2024-08-27
print(f'短日期格式:{e:%y-%b-%d}') # 短日期格式:24-Aug-27
print(f'短日期格式:{e:%y-%B-%d}') # 短日期格式:24-August-27
将系统日期格式化为长日期。下面使用 f-string 将当前系统日期格式化为长日期格式,代码如下:
import datetime
e = datetime.datetime.today()
# 当前系统日期: 2024-08-27 07:16:24.115475
print('当前系统日期:', e) # 当期系统日期
# 长日期格式:2024年08月27日
print(f'长日期格式:{e:%Y年%m月%d日}') # 长日期格式
根据系统日期返回星期几。f-string 可以根据系统日期返回星期(数字),相关介绍如下:
- %a:星期几(缩写),如
'Sun'
; - %A:星期几(全名),如
'Sunday'
; - %w:星期几(数字,0 是星期日、6 是星期六),如
'0'
- %u:星期几(数字,1 是星期一、7 是星期日),如
'7'
下面使用 f-string 中的 %w 返回当前系统日期的星期。由于返回的星期是数字,还需要通过自定义函数进行转换,0 表示星期日,依次排列直到星期六,代码如下:
import datetime
e = datetime.datetime.today() # 获取当前系统日期
# 定义数字星期返回星期几的函数
def get_week(date):
week_dict = {
0: '星期日',
1: '星期一',
2: '星期二',
3: '星期三',
4: '星期四',
5: '星期五',
6: '星期六',
}
day = int(f'{e:%w}') # 根据系统日期返回数字星期并转换为整型
return week_dict[day]
print(f'今天是:{e:%Y年%m月%d日}') # 长日期格式 今天是:2024年08月27日
print(get_week(datetime.datetime.today())) # 调用函数返回星期几 星期二
判断当前系统日期是今年的第几天第几周。f-string 可以根据当前系统日期返回一年中的第几天和第几周,相关介绍如下:
- %j:一年中的第几天(以0补足三位),如 2019年1月1日 返回
'001'
- %U:一年中的第几周(以全年首个周日后的星期为第 0 周,以 0 补足两位,如
'00'
),如'30'
- %W:一年中的第几周(以全年首个周一后的星期为第 0 周,以 0 补足两位,如
'00'
),如'30'
- %V:一年中的第几周(以全年首个星期为第 1 周,以 0 补足两位,如
'01'
),如'31'
下面分别使用 f-string 中的 %j 返回当前系统日期是一年中的第几天、使用 %U、%W 和 %V 返回当前系统日期是一年中的第几周,代码如下:
import datetime
e = datetime.datetime.today() # 获取当前系统日期
print(f'今天是:2024年的第{e:%j}天') # 今天是:2024年的第240天
print(f'今天是:2024年的第{e:%U}周') # 今天是:2024年的第34周
print(f'今天是:2024年的第{e:%W}周') # 今天是:2024年的第35周
print(f'今天是:2024年的第{e:%V}周') # 今天是:2024年的第35周
根据当前系统日期返回时间。f-string 可以根据当前系统日期返回时间,相关介绍如下:
- %H:小时(24小时制,以 0 补足两位),如
'14'
- %I:小时(12小时制,以 0 补足两位),如
'02'
- %p:上午/下午,如上午为
'AM'
,下午为'PM'
- %M:分钟(以 0 补足两位),如
'48'
- %S:秒(以 0 补足两位),如
'48'
- %f:微秒(以 0 补足六位),如
'734095'
下面根据当前系统日期返回时间,代码如下:
import datetime
e = datetime.datetime.today()
print(f'今天是:{e:%Y年%m月%d日}') # 长日期格式 今天是:2024年08月27日
print(f'时间是:{e:%H:%M:%S}') # 返回当前时间 时间是:07:24:46
print(f'时间是:{e:%H时%M分%S秒 %f微秒}') # 返回当前时间到微秒(24小时制) 时间是:07时24分46秒 691170微秒
print(f'时间是:{e:%p%I时%M分%S秒 %f微秒}') # 返回当前时间到微秒(12小时制)时间是:AM07时24分46秒 691170微秒