2024 Python3.10 系统入门+进阶(八):字符串及其常用操作详解下篇

一、字符串转换方法(用的少)

1.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())

1.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())

1.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

1.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

1.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!

1.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

1.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

1.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

二、字符对齐方法(用的少)

2.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, ' '))

2.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])))

2.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语言转义字符 进行学习。

3.1 字节串

在 Python 中,有两种常用的字符串类型,分别为 str 和 bytes。其中, str 表示 Unicode 字符(ASCII 或者其他),bytes 表示二进制数据(包括编码的文本)。这两种类型的字符串不能拼接在一起使用。通常情况下,str 在内存中以 Unicode 表示,一个字符对应若干个字节。但是如果在网络上传输,或者存到磁盘上,就需要把 str 转换为字节类型,即 bytes 类型。

字节串(bytes)也称字节序列,是不可变的序列,存储以字节为单位的数据。提示:bytes 类型是 Python3 新增的一种数据类型。字节串与字符串的比较:

  1. 字符串是由多个字符构成,以字符为单位进行操作。默认为 Unicode 字符,字符范围为 0~65535。字符串是字符序列,它是一种抽象的概念,不能直接存储在硬盘,用以显示供人阅读或操作。
  2. 字节串是由多个字节构成,以字节为单位进行操作。字节是整型值,取值范围 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'')

3.2 编码与解码

3.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

参数说明:

  1. str:表示要进行转换的字符串。
  2. encoding="utf-8":可选参数,用于指定进行转码时采用的编码,默认为 utf-8,如果想使用简体中文可以设置为 gbk 或 gb2312(与网站使用的编码方式有关)。当只有一个参数时,可省略前面的 encoding=,直接写编码。
  3. 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'))

3.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

参数说明:

  1. bytes:表示要进行转换的字节数据,通常是 encode() 方法转换的结果。
  2. encoding="utf-8":可选参数,用于指定进行解码时采用的字符编码,默认为 utf-8,如果想使用简体中文可以设置为 gbk 或 gb2312(与网站使用的编码方式有关)。当只有一个参数时,可省略前面的 encoding=,直接写编码。
  3. 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代码

四、切片

线性结构特征:

  1. 可迭代 for … in
  2. 有长度,通过len(x)获取,容器
  3. 通过整数下标可以访问元素。正索引、负索引,可以切片。

已经学习过的线性结构: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]]

五、格式化字符串

5.1 使用百分号“%”格式化字符串(在Python源码中会经常看到和后续日志模块中也会使用到所以也需要掌握)

参考文章 https://blog.csdn.net/xw1680/article/details/136889807十、Python格式化字符串(格式化输出) 中的 10.1 %运算符 小节。

5.2 format()函数与str.format()方法——格式化字符串

参考文章 https://blog.csdn.net/xw1680/article/details/136889807十、Python格式化字符串(格式化输出) 中的 10.2 str.format()方法10.3 format() 函数 小节。

5.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 可以实现将数字格式化为不同的进制数,省去了进制转换的麻烦,具体介绍如下:

  1. b:二进制整数格式
  2. d:十进制整数格式
  3. o:八进制整数格式
  4. x:十六进制整数格式(小写字母)
  5. 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 支持三种对齐方式:

  1. <:左对齐(字符串默认对齐方式);
  2. >:右对齐(数值默认对齐方式);
  3. ^:居中。

下面以以左对齐、右对齐和居中输出 听天色等烟雨而我在等你,固定宽度 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 对象,相关介绍如下:

  1. %d:表示日,是数字,以 0 补足两位
  2. %b:表示月(缩写)
  3. %B:表示月(全名)
  4. %m:表示月(数字,以 0 补足两位)
  5. %y:年(后两位数字,以 0 补足两位)
  6. %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 可以根据系统日期返回星期(数字),相关介绍如下:

  1. %a:星期几(缩写),如 'Sun'
  2. %A:星期几(全名),如 'Sunday'
  3. %w:星期几(数字,0 是星期日、6 是星期六),如 '0'
  4. %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 可以根据当前系统日期返回一年中的第几天和第几周,相关介绍如下:

  1. %j:一年中的第几天(以0补足三位),如 2019年1月1日 返回 '001'
  2. %U:一年中的第几周(以全年首个周日后的星期为第 0 周,以 0 补足两位,如 '00'),如 '30'
  3. %W:一年中的第几周(以全年首个周一后的星期为第 0 周,以 0 补足两位,如 '00'),如 '30'
  4. %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 可以根据当前系统日期返回时间,相关介绍如下:

  1. %H:小时(24小时制,以 0 补足两位),如 '14'
  2. %I:小时(12小时制,以 0 补足两位),如 '02'
  3. %p:上午/下午,如上午为 'AM',下午为 'PM'
  4. %M:分钟(以 0 补足两位),如 '48'
  5. %S:秒(以 0 补足两位),如 '48'
  6. %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微秒
  • 19
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Amo Xiang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值