Python中的字符串类型与操作详解
Python 3 中的 Unicode 字符串模型
自 Python 3 起,所有字符串默认采用 Unicode 编码。这意味着开发者可以直接在代码中使用中文、日文、阿拉伯文等多语言字符,而无需额外处理编码转换问题。字符串类型 str 表示的是 Unicode 文本,而原始字节数据则由 bytes 类型表示。两者之间需要通过编码(encode)和解码(decode)进行转换:
# 字符串编码为字节
text = "你好 World"
encoded = text.encode('utf-8') # 返回 bytes 对象
# 字节解码为字符串
decoded = encoded.decode('utf-8') # 恢复为 str
print(decoded) # 输出:你好 World
标识符合法性检查
方法 str.isidentifier() 可用于判断一个字符串是否符合 Python 标识符命名规则(如变量名、函数名),但不判断其是否为保留关键字。若需进一步确认是否为关键字,可结合 keyword 模块使用。
多行字符串与文档字符串
使用三重引号(''' 或 """)可以定义跨越多行的字符串。这类字符串常被用作函数或类的文档说明(docstring),并可通过 .__doc__ 属性访问。
def example():
"""
这是一个示例函数。
它展示了如何编写文档字符串。
"""
pass
print(example.__doc__)
转义字符详解
反斜杠 \ 是 Python 中的转义符号,用于表示特殊字符或避免语法冲突。例如,在单引号包围的字符串中包含单引号本身时,必须进行转义。
print('It\'s a beautiful day.') # 使用转义
print("She said: \"Hello!\"") # 双引号内嵌双引号
print('C:\\Users\\name\\file.txt') # Windows 路径中的反斜杠
print('First line.\nSecond line.') # 换行符 \n
print('Tab-separated:\tValue') # 制表符 \t
常见转义序列包括:\n(换行)、\t(制表)、\\(反斜杠)、\' 和 \"(引号),以及 \xhh(十六进制字符)等。
字符串格式化方式
1. 百分号 % 格式化(传统方式)
类似于 C 语言的 printf 风格,使用占位符与元组配合完成格式化。
name = "Alice"
age = 30
print("Hello, %s. You are %d years old." % (name, age))
常用格式符:
%s:任意对象转字符串%d:整数%f:浮点数%x/%X:十六进制输出(小写/大写)%%:输出百分号本身
2. format() 方法(推荐方式)
从 Python 2.6 开始引入,更加灵活且支持位置参数、关键字参数和索引引用。
# 位置参数
print("{}, {}, {}".format("a", "b", "c"))
# 索引指定
print("{2}, {1}, {0}".format("x", "y", "z"))
# 关键字参数
print("Name: {name}, Age: {age}".format(name="Bob", age=25))
# 填充与对齐
print("{:^10}".format("center")) # 居中,宽度10
print("{:<10}".format("left")) # 左对齐
print("{:>10}".format("right")) # 右对齐
# 数值格式化
print("{:.2f}".format(3.14159)) # 保留两位小数
print("{:,}".format(1000000)) # 千位分隔符
print("{:.1%}".format(0.875)) # 百分比显示
字符串操作符
| 操作符 | 说明 |
|---|---|
+ | 连接两个字符串 |
* | 重复字符串多次,如 "hi" * 3 → "hihihi" |
in, not in | 成员检测,判断子串是否存在 |
r"" | 原始字符串,禁用转义,适合正则表达式和路径 |
b"" | 生成 bytes 对象,用于二进制数据处理 |
常用内置函数与方法
大小写转换
s = "hello WORLD"
print(s.lower()) # hello world
print(s.upper()) # HELLO WORLD
print(s.capitalize()) # Hello world
print(s.title()) # Hello World
print(s.swapcase()) # HELLO world
查找与替换
text = "fast and faster"
print(text.find("fast")) # 0
print(text.rfind("fast")) # 9(从右往左找首次出现)
print(text.replace("fast", "slow", 1)) # slow and faster
前缀与后缀判断
filename = "data.csv"
if filename.endswith(".csv"):
print("This is a CSV file.")
if filename.startswith("data"):
print("Data file detected.")
长度与统计
s = "abracadabra"
print(len(s)) # 11
print(max(s)) # 'r'(ASCII 最大的字符)
print(min(s)) # 'a'
print(s.count("a")) # 5(字母 a 出现次数)
拆分与合并
words = "apple,banana,grape"
fruit_list = words.split(",") # ['apple', 'banana', 'grape']
joined = "|".join(fruit_list) # apple|banana|grape
print(joined)
空白处理
spaced = " hello "
print(spaced.strip()) # "hello"
print(spaced.lstrip()) # "hello "
print(spaced.rstrip()) # " hello"
对齐控制
word = "Python"
print(word.center(20, '-')) # -----Python-----
print(word.ljust(20, '*')) # Python**************
print(word.rjust(20, '>')) # >>>>>>>>>Python
类型判断方法
以下方法返回布尔值,常用于输入验证:
isalnum():仅包含字母和数字isalpha():仅包含字母isdigit():仅包含数字字符(支持 ASCII 数字)isnumeric():更广义的数字,包括全角数字、分数等isdecimal():仅十进制数字(最严格)isspace():仅空白字符(空格、\t、\n 等)islower(),isupper():全小写或全大写istitle():每个单词首字母大写