Python 字符串
Python 字符串
Section titled “Python 字符串”字符串是 Python 中最基本和常用的数据类型之一。它们代表字符序列。
通过将字符括在单引号 ('...')、双引号 ("...") 或三引号 ('''...''' 或 """...""") 中来创建字符串。单引号和双引号对于单行字符串是等效的。三引号允许字符串跨越多行。
single_quoted = 'Hello World!'double_quoted = "Python Programming"multi_line = '''This is a stringspanning multiplelines.'''
print(single_quoted)print(double_quoted)print(multi_line)在 Python 3 中,字符串原生支持 Unicode 字符。
访问字符和子字符串(切片)
Section titled “访问字符和子字符串(切片)”字符串是序列,因此您可以使用索引(从 0 开始)通过方括号 [] 访问单个字符。您还可以使用切片 [start:stop:step] 提取子字符串。
#!/usr/bin/env python3
my_string = "Python Programming"
# Access individual characters# 访问单个字符print(f"my_string[0]: {my_string[0]}") # Output: P# 输出: Pprint(f"my_string[7]: {my_string[7]}") # Output: P# 输出: Pprint(f"my_string[-1]: {my_string[-1]}") # Output: g (last character)# 输出: g (最后一个字符)print(f"my_string[-3]: {my_string[-3]}") # Output: i (third from end)# 输出: i (倒数第三个字符)
# Slicing [start:stop] (stop index is exclusive)# 切片 [start:stop] (stop 索引是排他的)print(f"my_string[0:6]: {my_string[0:6]}") # Output: Python# 输出: Pythonprint(f"my_string[7:18]: {my_string[7:18]}") # Output: Programming# 输出: Programming
# Slicing shortcuts# 切片快捷方式print(f"my_string[:6]: {my_string[:6]}") # Output: Python (from beginning to index 5)# 输出: Python (从开头到索引 5)print(f"my_string[7:]: {my_string[7:]}") # Output: Programming (from index 7 to end)# 输出: Programming (从索引 7 到结尾)print(f"my_string[:]: {my_string[:]}") # Output: Python Programming (a copy of the whole string)# 输出: Python Programming (整个字符串的副本)
# Slicing with step [start:stop:step]# 带步长的切片 [start:stop:step]print(f"my_string[::2]: {my_string[::2]}") # Output: Pto rgamn (every second character)# 输出: Pto rgamn (每隔一个字符)print(f"my_string[::-1]: {my_string[::-1]}")# Output: gnimmargorP nohtyP (reverse the string)# 输出: gnimmargorP nohtyP (反转字符串)字符串的不可变性
Section titled “字符串的不可变性”Python 中的字符串是不可变的,这意味着您在创建字符串对象后不能原地修改它。看起来修改字符串的操作实际上是创建并返回一个新的字符串对象。
#!/usr/bin/env python3
message = "Hello World!"print(f"Original message: {message}, ID: {id(message)}")# 原始消息,ID
# This creates a NEW string# 这创建了一个新的字符串new_message = message[:6] + "Python!"print(f"New message: {new_message}, ID: {id(new_message)}")# 新消息,ID
# Attempting to change a character directly causes an error:# 尝试直接修改字符会导致错误:# message[0] = 'J' # Raises TypeError: 'str' object does not support item assignment# 引起 TypeError: 'str' 对象不支持项目赋值反斜杠 (\) 用于转义具有特殊含义或不可打印的字符。
| 表示法 | 描述 |
|---|---|
\n | 换行符 |
\t | 水平制表符 |
\r | 回车符 |
\b | 退格符 |
\f | 换页符 |
\' | 单引号 |
\" | 双引号 |
\\ | 反斜杠本身 |
\xhh | 十六进制值为 hh 的字符 |
\uxxxx | 十六进制值为 xxxx 的 16 位 Unicode 字符 |
\Uxxxxxxxx | 十六进制值为 xxxxxxxx 的 32 位 Unicode 字符 |
\ooo | 八进制值为 ooo 的字符 (较少使用) |
示例:
print("First line\nSecond line")print("Path: C:\\Users\\Name")print('He said, \'Hello!\'')在字符串字面量前加上 r 或 R 可以创建一个原始字符串,其中反斜杠被视为普通字符,而不是转义序列。这对于正则表达式和 Windows 文件路径特别有用。
print(r"This is a raw string.\nNo newline here.")# Output: This is a raw string.\nNo newline here.# 输出: This is a raw string.\nNo newline here.
print(R"C:\Users\Name\Documents")# Output: C:\Users\Name\Documents# 输出: C:\Users\Name\Documents注意:原始字符串不能以单个反斜杠结尾。
字符串运算符
Section titled “字符串运算符”适用于字符串的常用运算符:
| 运算符 | 名称 | 描述 | 示例 |
|---|---|---|---|
+ | 拼接 | 连接两个字符串 | 'Hello' + ' ' + 'World' -> 'Hello World' |
* | 重复 | 重复字符串 | 'Hi!' * 3 -> 'Hi!Hi!Hi!' |
[] | 索引 | 访问单个字符 | 'Python'[0] -> 'P' |
[:] | 切片 | 提取子字符串 | 'Python'[1:4] -> 'yth' |
in | 成员资格 | 检查子字符串是否存在 | 'th' in 'Python' -> True |
not in | 成员资格 | 检查子字符串是否不存在 | 'x' not in 'Python' -> True |
字符串格式化
Section titled “字符串格式化”创建带有嵌入变量值的字符串至关重要。现代 Python 提供了几种方法:
1. f-字符串(格式化字符串字面量)- 推荐(Python 3.6+)
Section titled “1. f-字符串(格式化字符串字面量)- 推荐(Python 3.6+)”在字符串前加上 f 或 F。将表达式嵌入到花括号 {} 中。
name = "Alice"age = 30pi = 3.14159
# Basic usage# 基本用法print(f"My name is {name} and I am {age} years old.")
# Expressions inside braces# 花括号内的表达式print(f"Next year, I will be {age + 1}.")
# Formatting specifiers (after colon :)# 格式化说明符 (冒号后 :)print(f"Pi is approximately {pi:.2f}") # Format float to 2 decimal places# 格式化浮点数到小数点后 2 位print(f"Age: {age:03d}") # Pad integer with leading zeros to width 3# 整数前补零到宽度 3print(f"Name aligned: '{name:<10}'") # Left-align in a field of 10 chars# 在 10 个字符的字段中左对齐print(f"Name aligned: '{name:>10}'") # Right-align# 右对齐print(f"Name aligned: '{name:^10}'") # Center-align# 居中对齐2. str.format() 方法
Section titled “2. str.format() 方法”在字符串中使用花括号 {} 作为占位符,并调用 format() 方法。
name = "Bob"age = 25
# Positional arguments# 位置参数print("Name: {}, Age: {}".format(name, age))
# Keyword arguments# 关键字参数print("Name: {n}, Age: {a}".format(n=name, a=age))
# Indexed arguments# 索引参数print("Name: {0}, Age: {1}, Repeat Name: {0}".format(name, age))
# Formatting specifiers (similar to f-strings)# 格式化说明符 (类似于 f-字符串)print("Value: {:.3f}".format(10/3)) # Output: Value: 3.333# 输出: Value: 3.3333. % 运算符(旧式)
Section titled “3. % 运算符(旧式)”使用 % 占位符(例如 %s 表示字符串,%d 表示整数,%f 表示浮点数),类似于 C 语言的 printf。与 f-字符串或 str.format() 相比,它灵活性较低,且容易出错,因此不建议在新代码中使用。
name = "Charlie"age = 42
print("My name is %s and weight is %d kg!" % (name, age))
# Formatting specifiers# 格式化说明符print("Value: %.2f" % (12.3456)) # Output: Value: 12.35# 输出: Value: 12.35% 格式化代码表(供参考):
| 格式符号 | 转换 |
|---|---|
%c | 单个字符 |
%s | 字符串(或任何使用 str() 的对象) |
%d 或 %i | 有符号十进制整数 |
%u | 已废弃(同 %d) |
%o | 八进制整数 |
%x | 十六进制整数(小写) |
%X | 十六进制整数(大写) |
%f | 浮点十进制数 |
%e | 指数表示法(小写 ‘e’) |
%E | 指数表示法(大写 ‘E’) |
%g | %f 和 %e 中较短者 |
%G | %f 和 %E 中较短者 |
%% | 字面量 ’%’ 字符 |
内置字符串方法
Section titled “内置字符串方法”Python 字符串有一组丰富的内置方法用于常见操作。请记住,这些方法返回新的字符串;它们不会修改原始字符串。
常用字符串方法:
| 方法 | 描述 |
|---|---|
capitalize() | 返回首字母大写、其余小写的副本。 |
casefold() | 返回一个 casefolded 副本(用于无视大小写匹配的激进小写转换)。 |
center(width[, fillchar]) | 返回在 width 内居中的字符串,用 fillchar 填充(默认为空格)。 |
count(sub[, start[, end]]) | 返回子字符串 sub 的非重叠出现次数。 |
encode(encoding='utf-8', errors='strict') | 返回表示按 encoding 编码的字符串的 bytes 对象。 |
endswith(suffix[, start[, end]]) | 如果字符串以 suffix 结尾,返回 True。 |
expandtabs(tabsize=8) | 返回将制表符 (\t) 替换为空格的副本。 |
find(sub[, start[, end]]) | 返回找到 sub 的最低索引,如果未找到则返回 -1。 |
index(sub[, start[, end]]) | 类似于 find(),但如果未找到 sub 则引发 ValueError。 |
isalnum() | 如果所有字符都是字母数字且至少有一个字符,返回 True。 |
isalpha() | 如果所有字符都是字母且至少有一个字符,返回 True。 |
isascii() | 如果字符串为空或所有字符都是 ASCII 字符,返回 True。 |
isdecimal() | 如果所有字符都是十进制数字且至少有一个字符,返回 True。 |
isdigit() | 如果所有字符都是数字且至少有一个字符,返回 True。 |
isidentifier() | 如果字符串是有效的 Python 标识符,返回 True。 |
islower() | 如果所有大小写字符都是小写且至少有一个大小写字符,返回 True。 |
isnumeric() | 如果所有字符都是数字字符且至少有一个字符,返回 True。 |
isprintable() | 如果所有字符都是可打印的或字符串为空,返回 True。 |
isspace() | 如果所有字符都是空白字符且至少有一个字符,返回 True。 |
istitle() | 如果字符串是标题化格式且至少有一个字符,返回 True。 |
isupper() | 如果所有大小写字符都是大写且至少有一个大小写字符,返回 True。 |
join(iterable) | 使用字符串作为分隔符连接 iterable 中的元素(必须是字符串)。 |
ljust(width[, fillchar]) | 返回在 width 内左对齐的字符串。 |
lower() | 返回所有大小写字符转换为小写的副本。 |
lstrip([chars]) | 返回移除前导字符(默认为空白字符)的副本。 |
maketrans(x[, y[, z]]) | 返回用于 translate() 的转换表。 |
partition(sep) | 在第一次出现 sep 的位置分割字符串,返回元组 (before, sep, after)。 |
removeprefix(prefix) | 如果字符串以 prefix 开头,则返回移除 prefix 后的副本 (Python 3.9+)。 |
removesuffix(suffix) | 如果字符串以 suffix 结尾,则返回移除 suffix 后的副本 (Python 3.9+)。 |
replace(old, new[, count]) | 返回将 old 替换为 new 的副本(可选地最多替换 count 次)。 |
rfind(sub[, start[, end]]) | 类似于 find(),但从右边开始搜索。 |
rindex(sub[, start[, end]]) | 类似于 index(),但从右边开始搜索。 |
rjust(width[, fillchar]) | 返回在 width 内右对齐的字符串。 |
rpartition(sep) | 类似于 partition(),但在最后一次出现 sep 的位置分割。 |
rsplit(sep=None, maxsplit=-1) | 类似于 split(),但从右边开始分割。 |
rstrip([chars]) | 返回移除尾随字符(默认为空白字符)的副本。 |
split(sep=None, maxsplit=-1) | 使用 sep 作为分隔符(默认为空白字符)分割字符串并返回单词列表,最多分割 maxsplit 次。 |
splitlines(keepends=False) | 按行边界分割字符串并返回行的列表。 |
startswith(prefix[, start[, end]]) | 如果字符串以 prefix 开头,返回 True。 |
strip([chars]) | 返回移除前导/尾随字符(默认为空白字符)的副本。 |
swapcase() | 返回将大写字符转换为小写、小写字符转换为大写的副本。 |
title() | 返回标题化版本(单词首字母大写,其余小写)。 |
translate(table) | 返回通过 table(由 maketrans 生成)映射字符的副本。 |
upper() | 返回所有大小写字符转换为大写的副本。 |
zfill(width) | 返回左侧填充 ‘0’ 到指定 width 的副本。 |
方法使用示例:
text = " Hello World! "
print(f"Original: '{text}'")# 原始字符串print(f"strip(): '{text.strip()}'")print(f"lower(): '{text.lower()}'")print(f"upper(): '{text.upper()}'")print(f"replace('o', 'X'): '{text.replace('o', 'X')}'")print(f"split(): {text.split()}") # Splits by whitespace# 按空白字符分割
words = ["Python", "is", "fun"]separator = " "print(f"join(): '{separator.join(words)}'")
print(f"startswith(' H'): {text.startswith(' H')}")print(f"find('World'): {text.find('World')}")