目录
字符串访问操作总结
在 Python 中,访问字符串中的值主要通过索引和切片操作来实现。
操作 | 描述 | 示例 |
---|---|---|
str[index] | 通过索引访问字符串中的单个字符 | "hello"[1] → 'e' |
str[start:end] | 通过切片访问子字符串 | "hello"[1:4] → 'ell' |
str[:end] | 从字符串开始到指定结束索引(不包括结束索引) | "hello"[:3] → 'hel' |
str[start:] | 从指定开始索引到字符串末尾 | "hello"[2:] → 'llo' |
str[start:end:step] | 通过切片访问字符串的步长子字符串 | "hello"[::2] → 'hlo' |
str[-index] | 通过负索引从字符串末尾访问字符 | "hello"[-1] → 'o' |
str[-start:-end] | 通过负索引访问子字符串 | "hello"[-4:-1] → 'ell' |
示例代码
text = "hello"
# 访问单个字符
print(text[1]) # 输出: 'e'
print(text[-1]) # 输出: 'o'
# 访问子字符串
print(text[1:4]) # 输出: 'ell'
print(text[:3]) # 输出: 'hel'
print(text[2:]) # 输出: 'llo'
# 切片和步长
print(text[::2]) # 输出: 'hlo'
print(text[::-1]) # 输出: 'olleh'(反转字符串)
# 负索引访问
print(text[-4:-1]) # 输出: 'ell'
说明
- 正索引: 从字符串的开头开始,索引从
0
开始递增。 - 负索引: 从字符串的末尾开始,索引从
-1
开始递减。 - 切片: 通过
start:end
的格式来获取子字符串。start
包括在内,end
不包括在内。 - 步长: 切片中的
step
参数用于指定步长。默认步长是1
,可以用于跳过字符或反向切片(例如[::-1]
用于反转字符串)。
字符串更新方法总结
在 Python 中,字符串是不可变的(immutable),这意味着一旦创建了一个字符串,就无法直接修改它。如果需要“更新”字符串,实际上是创建一个新的字符串。可以通过多种方法来生成新的字符串,包括字符串拼接、替换、格式化等。
操作 | 描述 | 示例 |
---|---|---|
str.replace(old, new) | 替换字符串中的子串 old 为 new | "hello world".replace("world", "Python") → "hello Python" |
str.join(iterable) | 使用指定的分隔符连接 iterable 中的元素 | ",".join(["a", "b", "c"]) → "a,b,c" |
str.format(*args, **kwargs) | 格式化字符串,用指定的值替换 {} 占位符 | "Hello, {}".format("Alice") → "Hello, Alice" |
f-string (格式化字符串) | 用大括号 {} 替换变量 | name = "Alice"; f"Hello, {name}" → "Hello, Alice" |
str.zfill(width) | 在字符串左侧填充零,使其长度达到 width | "42".zfill(5) → "00042" |
字符串切片和拼接 | 使用切片和拼接操作创建新字符串 | "hello"[0:3] + "world" → "helworld" |
示例代码
# 使用 replace 更新字符串
text = "hello world"
new_text = text.replace("world", "Python")
print(new_text) # 输出: "hello Python"
# 使用 join 连接字符串
words = ["a", "b", "c"]
joined_text = ",".join(words)
print(joined_text) # 输出: "a,b,c"
# 使用 format 更新字符串
greeting = "Hello, {}"
name = "Alice"
formatted_text = greeting.format(name)
print(formatted_text) # 输出: "Hello, Alice"
# 使用 f-string 更新字符串
name = "Alice"
f_string_text = f"Hello, {name}"
print(f_string_text) # 输出: "Hello, Alice"
# 使用 zfill 填充零
number = "42"
padded_number = number.zfill(5)
print(padded_number) # 输出: "00042"
# 使用切片和拼接创建新字符串
original = "hello"
updated = original[0:3] + "world"
print(updated) # 输出: "helworld"
说明
str.replace(old, new)
: 替换所有old
子串为new
。返回一个新的字符串。str.join(iterable)
: 将iterable
中的元素连接成一个新的字符串,以str
作为分隔符。str.format(*args, **kwargs)
: 使用指定的值替换字符串中的{}
占位符。- f-string: 在 Python 3.6 及更高版本中,使用 f-string 进行字符串插值,语法更简洁。
str.zfill(width)
: 在字符串的左侧填充零,使其总长度达到width
。- 切片和拼接: 利用切片操作和字符串拼接创建新的字符串。
常见转义字符
在 Python 中,转义字符用于在字符串中插入特殊字符,例如换行符、制表符等。转义字符以反斜杠(\
)开头。
转义字符 | 描述 | 示例 |
---|---|---|
\\ | 反斜杠字符(\) | “This is a backslash: \” |
\’ | 单引号字符(') | “It's a great day” |
\" | 双引号字符(") | “He said, "Hello!"” |
\n | 换行符 | “Hello\nWorld” → Hello (换行) World |
\r | 回车符 | “Hello\rWorld” → World (覆盖 Hello) |
\t | 制表符 | “Name:\tAlice” → Name: Alice |
\b | 退格符 | “Hello\bWorld” → HellWorld |
\f | 换页符 | “Page1\fPage2” |
\uXXXX | Unicode 字符(4 位十六进制数) | “\u2603” → ☃ |
\UXXXXXXXX | Unicode 字符(8 位十六进制数) | “\U0001F600” → 😀 |
\a | 响铃符 | “Hello\aWorld” |
\v | 垂直制表符 | “Hello\vWorld” |
示例代码
# 反斜杠字符
text = "This is a backslash: \\"
print(text) # 输出: "This is a backslash: \"
# 单引号字符
text = "It's a great day"
print(text) # 输出: "It's a great day"
# 双引号字符
text = "He said, \"Hello!\""
print(text) # 输出: "He said, "Hello!""
# 换行符
text = "Hello\nWorld"
print(text)
# 输出:
# Hello
# World
# 回车符
text = "Hello\rWorld"
print(text) # 输出: "World" (覆盖 "Hello")
# 制表符
text = "Name:\tAlice"
print(text) # 输出: "Name: Alice"
# 退格符
text = "Hello\bWorld"
print(text) # 输出: "HellWorld"
# 换页符
text = "Page1\fPage2"
print(text) # 输出: "Page1" (换页) "Page2"
# Unicode 字符
text1 = "\u2603" # Unicode 雪人符号
text2 = "\U0001F600" # Unicode 微笑符号
print(text1) # 输出: "☃"
print(text2) # 输出: "😀"
# 响铃符
text = "Hello\aWorld"
print(text) # 输出: "Hello" (可能会发出响铃声) "World"
# 垂直制表符
text = "Hello\vWorld"
print(text) # 输出: "Hello" (垂直间距) "World"
说明
- 反斜杠字符 (
\\
): 用于在字符串中插入一个反斜杠。 - 单引号字符 (
\'
) 和 双引号字符 (\"
): 用于在字符串中插入引号。 - 换行符 (
\n
): 在字符串中插入换行。 - 回车符 (
\r
): 将光标移动到行的开头(常用于覆盖文本)。 - 制表符 (
\t
): 插入水平制表符,用于对齐文本。 - 退格符 (
\b
): 删除前一个字符(实际效果可能依赖于环境)。 - 换页符 (
\f
): 插入换页符,用于分页。 - Unicode 字符 (
\uXXXX
和\UXXXXXXXX
): 插入 Unicode 字符,适用于各种语言和符号。 - 响铃符 (
\a
): 发出系统提示声音(取决于系统)。 - 垂直制表符 (
\v
): 插入垂直制表符,较少使用。
字符串运算符总结
在 Python 中,字符串运算符用于对字符串进行基本的操作和计算。这些运算符包括连接、重复、比较等。
操作符 | 描述 | 示例 |
---|---|---|
+ | 字符串连接(拼接) | "Hello " + “World” → “Hello World” |
* | 字符串重复 | “Hello” * 3 → “HelloHelloHello” |
in | 判断子串是否存在于字符串中 | “lo” in “Hello” → True |
not in | 判断子串是否不在字符串中 | “lo” not in “Hello” → False |
== | 比较两个字符串是否相等 | “hello” == “hello” → True |
!= | 比较两个字符串是否不相等 | “hello” != “world” → True |
> | 比较两个字符串的字典序 | “apple” > “banana” → False |
< | 比较两个字符串的字典序 | “apple” < “banana” → True |
>= | 比较两个字符串的字典序(大于等于) | “apple” >= “apple” → True |
<= | 比较两个字符串的字典序(小于等于) | “apple” <= “banana” → True |
[] | 通过索引获取字符串中字符 | a[1] 输出结果 e |
[ : ] | 截取字符串中的一部分,遵循左闭右开原则,str[0,2] 是不包含第 3 个字符的。 | a[1:4] 输出结果 ell |
in | 成员运算符 - 如果字符串中包含给定的字符返回 True | ‘H’ in a 输出结果 True |
not in | 成员运算符 - 如果字符串中不包含给定的字符返回 True | ‘M’ not in a 输出结果 True |
r/R | 原始字符串 - 原始字符串:所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符。 原始字符串除在字符串的第一个引号前加上字母 r(可以大小写)以外,与普通字符串有着几乎完全相同的语法。 | print( r'\\n' ) print( R'\\n' ) |
% | 格式字符串 - 用于字符串格式化 | 请看下一节内容。 |
示例代码
# 字符串运算符示例
# 字符串连接
str1 = "Hello "
str2 = "World"
result = str1 + str2
print(f'字符串连接: {result}') # 输出: Hello World
# 字符串重复
str3 = "Hello"
result = str3 * 3
print(f'字符串重复: {result}') # 输出: HelloHelloHello
# 判断子串是否存在于字符串中
str4 = "Hello"
print(f'判断子串是否存在: "lo" in "{str4}" → {"lo" in str4}') # 输出: True
# 判断子串是否不在字符串中
print(f'判断子串是否不在: "lo" not in "{str4}" → {"lo" not in str4}') # 输出: False
# 比较两个字符串是否相等
str5 = "hello"
print(f'比较两个字符串是否相等: "{str5}" == "hello" → {str5 == "hello"}') # 输出: True
# 比较两个字符串是否不相等
print(f'比较两个字符串是否不相等: "{str5}" != "world" → {str5 != "world"}') # 输出: True
# 比较两个字符串的字典序
str6 = "apple"
str7 = "banana"
print(f'比较两个字符串的字典序 (>): "{str6}" > "{str7}" → {str6 > str7}') # 输出: False
print(f'比较两个字符串的字典序 (<): "{str6}" < "{str7}" → {str6 < str7}') # 输出: True
# 比较两个字符串的字典序(大于等于)
print(f'比较两个字符串的字典序 (>=): "{str6}" >= "{str6}" → {str6 >= str6}') # 输出: True
# 比较两个字符串的字典序(小于等于)
print(f'比较两个字符串的字典序 (<=): "{str6}" <= "{str7}" → {str6 <= str7}') # 输出: True
# 通过索引获取字符串中字符
str8 = "Hello"
print(f'通过索引获取字符串中字符: {str8[1]}') # 输出: e
# 截取字符串中的一部分
print(f'截取字符串中的一部分: {str8[1:4]}') # 输出: ell
# 成员运算符 - 判断子串是否存在
print(f'成员运算符 (in): "H" in "{str8}" → {"H" in str8}') # 输出: True
# 成员运算符 - 判断子串是否不在
print(f'成员运算符 (not in): "M" not in "{str8}" → {"M" not in str8}') # 输出: True
# 原始字符串
print(f'原始字符串 (r): {r"\\n"}') # 输出: \\n
print(f'原始字符串 (R): {R"\\n"}') # 输出: \\n
# 格式字符串
name = "Alice"
age = 30
formatted_str = "Name: %s, Age: %d" % (name, age)
print(f'格式字符串 (%): {formatted_str}') # 输出: Name: Alice, Age: 30
说明
- 字符串连接 (
+
): 合并两个字符串。 - 字符串重复 (
*
): 重复字符串若干次。 - 成员运算符 (
in
,not in
): 检查子串是否在字符串中。 - 字典序比较 (
>
,<
,>=
,<=
): 比较字符串的字典序。 - 索引 (
[]
): 获取字符串中特定位置的字符。 - 切片 (
[:]
): 提取字符串的一部分。 - 原始字符串 (
r
,R
): 忽略转义字符,直接按字面意思处理字符串。 - 格式字符串 (
%
): 插入变量到字符串中。
字符串格式化
1. 使用 %
运算符(老式格式化)
这种方法是 Python 中最早的格式化方法,使用 %
运算符插入变量到字符串中。
示例代码:
name = "Alice"
age = 30
# 使用 % 运算符进行格式化
formatted_str = "Name: %s, Age: %d" % (name, age)
print(formatted_str) # 输出: Name: Alice, Age: 30
%s
用于字符串%d
用于整数%f
用于浮点数
2. 使用 str.format()
方法
这种方法是 Python 2.7 及其之后版本引入的,提供了更强大的格式化功能。
示例代码:
name = "Alice"
age = 30
# 使用 str.format() 方法进行格式化
formatted_str = "Name: {}, Age: {}".format(name, age)
print(formatted_str) # 输出: Name: Alice, Age: 30
# 使用索引
formatted_str = "Name: {0}, Age: {1}".format(name, age)
print(formatted_str) # 输出: Name: Alice, Age: 30
# 使用关键字参数
formatted_str = "Name: {name}, Age: {age}".format(name=name, age=age)
print(formatted_str) # 输出: Name: Alice, Age: 30
3. 使用 f-string(格式化字符串字面量)
这种方法是 Python 3.6 引入的,提供了最简洁和高效的格式化方式。通过在字符串前加 f
,可以直接在字符串中嵌入变量。
示例代码:
name = "Alice"
age = 30
# 使用 f-string 进行格式化
formatted_str = f"Name: {name}, Age: {age}"
print(formatted_str) # 输出: Name: Alice, Age: 30
4. 使用 Template
类(模板字符串)
这种方法通过 string
模块提供,适用于简单的字符串模板替换。与 %
和 str.format()
方法相比,Template
更适合动态内容插入。
示例代码:
from string import Template
name = "Alice"
age = 30
# 使用 Template 类进行格式化
template = Template("Name: $name, Age: $age")
formatted_str = template.substitute(name=name, age=age)
print(formatted_str) # 输出: Name: Alice, Age: 30
格式化选项
- 对齐和宽度:可以设置字段宽度和对齐方式,例如
"{:10}"
、"{:<10}"
、"{:>10}"
。 - 精度:控制浮点数的小数点后位数,例如
"{:.2f}"
。
示例代码:
number = 123.4567
# 使用 f-string 设置精度
formatted_str = f"Number: {number:.2f}"
print(formatted_str) # 输出: Number: 123.46
# 使用 str.format() 设置宽度和对齐
formatted_str = "{:<10} | {:^10} | {:>10}".format("left", "center", "right")
print(formatted_str) # 输出: left | center | right
Python三引号
在 Python 中,三引号('''
或 """
)用于创建多行字符串或文档字符串(docstrings)。三引号可以是单引号或双引号,它们的主要用途包括:
-
多行字符串:当你需要在字符串中包含多行文本时,三引号特别有用。
-
文档字符串(docstrings):用作函数、类或模块的文档注释。Python 的文档字符串用于描述代码的功能,通常被工具(如
help()
函数和文档生成器)用来生成文档。
使用三引号的示例
1. 多行字符串
使用三引号定义的字符串可以包含换行符和其他特殊字符,且不会影响字符串的格式。
示例代码:
# 使用单引号的多行字符串
multiline_string = '''这是一个多行字符串示例。
可以包含换行符和特殊字符。
这不会影响字符串的格式。'''
print(multiline_string)
输出:
这是一个多行字符串示例。
可以包含换行符和特殊字符。
这不会影响字符串的格式。
2. 文档字符串(Docstrings)
文档字符串用于描述函数、类或模块的功能,通常放在定义的顶部。它们是 Python 的一种特殊字符串,提供了内联文档支持。
示例代码:
def greet(name):
"""
函数说明:
这个函数接受一个名字作为参数,并打印一个问候消息。
参数:
name (str): 需要问候的名字
返回:
None
"""
print(f"Hello, {name}!")
# 查看函数的文档字符串
print(greet.__doc__)
输出:
函数说明:
这个函数接受一个名字作为参数,并打印一个问候消息。
参数:
name (str): 需要问候的名字
返回:
None
三引号的特点
- 保持格式:三引号内的内容会保持原有格式,包括换行和空格。
- 适用范围:可以用于包含多行文本的字符串,或在函数、类或模块的顶部作为文档字符串。
- 自动换行:三引号字符串的换行会保留在字符串中,但在实际应用中可以根据需要去除。
Unicode 字符串
在 Python 中,Unicode 是一种字符编码标准,用于表示几乎所有语言中的字符。Unicode 使得不同语言和符号能够统一处理,避免了不同编码方式之间的不兼容问题。Python 3 默认使用 Unicode 字符串,因此你可以直接处理各种字符而不需要特别的编码转换。
Unicode 字符串基本用法
1. 定义 Unicode 字符串
在 Python 3 中,你可以使用普通的字符串语法('
或 "
)定义 Unicode 字符串,无需额外的前缀。例如:
# 定义 Unicode 字符串
unicode_string = "你好,世界!" # 包含中文字符
print(unicode_string)
2. 字符编码
在 Python 3 中,所有字符串都是 Unicode 编码的。你可以使用 encode()
方法将 Unicode 字符串转换为其他编码格式,例如 UTF-8。
# 将 Unicode 字符串编码为 UTF-8
utf8_encoded = unicode_string.encode('utf-8')
print(utf8_encoded) # 输出:b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81'
你也可以使用 decode()
方法将编码后的字节串转换回 Unicode 字符串:
# 将 UTF-8 编码的字节串解码为 Unicode 字符串
decoded_string = utf8_encoded.decode('utf-8')
print(decoded_string) # 输出:你好,世界!
Unicode 转义字符
Unicode 字符可以使用转义序列在字符串中表示,这种表示方法对于特定字符集非常有用。
1. Unicode 转义序列
\uXXXX
:4 位十六进制数的 Unicode 转义序列(范围:\u0000
到\uFFFF
)\UXXXXXXXX
:8 位十六进制数的 Unicode 转义序列(范围:\U00000000
到\U0010FFFF
)
示例代码:
# Unicode 字符的转义序列
unicode_char1 = "\u4F60\u597D" # 你好
unicode_char2 = "\U0001F600" # 😀 (笑脸)
print(unicode_char1) # 输出:你好
print(unicode_char2) # 输出:😀
使用 Unicode 处理不同语言
Python 的 Unicode 支持使得处理各种语言的字符变得简单。例如,你可以处理中文、日文、韩文等字符,而不会遇到编码问题。
示例代码:
# 包含不同语言的 Unicode 字符串
chinese_text = "这是中文"
japanese_text = "これは日本語です"
korean_text = "이것은 한국어입니다"
print(chinese_text) # 输出:这是中文
print(japanese_text) # 输出:これは日本語です
print(korean_text) # 输出:이것은 한국어입니다
编码和解码示例
编码为 UTF-8 并解码:
# 原始 Unicode 字符串
original_string = "Hello, 世界!"
# 编码为 UTF-8
encoded_string = original_string.encode('utf-8')
print(f'Encoded: {encoded_string}')
# 解码为 Unicode 字符串
decoded_string = encoded_string.decode('utf-8')
print(f'Decoded: {decoded_string}')
输出:
Encoded: b'Hello, \xe4\xb8\x96\xe7\x95\x8c!'
Decoded: Hello, 世界!
总结
- 在 Python 3 中,所有字符串都是 Unicode 编码。
- 使用
encode()
和decode()
方法可以进行编码和解码操作。 - Unicode 转义序列允许在字符串中直接使用 Unicode 字符。
- Python 的 Unicode 支持使得处理多语言文本变得简单高效。
Python 的字符串内建函数
语法 | 解释 | Python代码示例 |
---|---|---|
count(str, beg= 0,end=len(string)) | 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数 | result = "hello".count("l", 1, 3) |
bytes.decode(encoding=“utf-8”, errors=“strict”) | Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象 | bytes_data = b"hello" result = bytes_data.decode("utf-8") |
encode(encoding=‘UTF-8’,errors=‘strict’) | 以 encoding 指定的编码格式编码字符串,如果出错默认报一个 ValueError 的异常,除非 errors 指定的是’ignore’或者’replace’ | result = "hello".encode("UTF-8") |
endswith(suffix, beg=0, end=len(string)) | 检查字符串是否以 obj 结束,如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束,如果是,返回 True,否则返回 False. | result = "hello".endswith("llo", 1, 4) |
find(str, beg=0 end=len(string)) | 检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1 | result = "hello".find("l", 1, 3) |
isdigit() | 如果字符串只包含数字则返回 True 否则返回 False… | result = "123".isdigit() |
isnumeric() | 如果字符串中只包含数字字符,则返回 True,否则返回 False | result = "123".isnumeric() |
join(seq) | 以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串 | result = "-".join(["a", "b", "c"]) |
maketrans() | 创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。 | trans_table = str.maketrans("abc", "def") |
replace(old, new [, max]) | 把 将字符串中的 str1 替换成 str2,如果 max 指定,则替换不超过 max 次。 | result = "hello".replace("l", "L", 2) |
split(str=“”, num=string.count(str)) | 以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串 | result = "a,b,c,d".split(",", 2) |
startswith(substr, beg=0,end=len(string)) | 检查字符串是否是以指定子字符串 substr 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查。 | result = "hello".startswith("he", 1, 3) |
strip([chars]) | 删除左右两边的空格或指定字符 | result = " hello world ".strip() |
translate(table, deletechars=“”) | 根据 str 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中 | trans_table = str.maketrans("abc", "def", "xyz") result = "abcxyzdef".translate(trans_table) |
str3 = "先帝知臣谨慎,故临崩寄臣以大事也。"
str4 = "*" * len(str3) # 生成一个与 str3 等长的全为 "*" 的字符串
print(str3) # 输出原始字符串
print(str4) # 输出与 str3 等长的 "*" 字符串
# 创建一个转换表,用于将 "临" 替换为 "*",将 "崩" 替换为 "*"
str5 = str3.maketrans("临崩", "**")
# 使用 translate 方法进行替换
str6 = str3.translate(str5) # 将 str3 中的 "临" 和 "崩" 替换为 "*"
print(str6) # 输出替换后的字符串
str7 = " 枫雪 "
print(str7.strip()) # 去掉 str7 两端的空格
print(str3.endswith("事也。")) # 检查 str3 是否以 "事也。" 结尾
print("&".join(str3)) # 用 "&" 将 str3 中的每个字符连接起来