字符串作为Python中最基础也最常用的数据类型之一,几乎出现在所有Python程序中。从简单的变量存储到复杂的文本处理,字符串都扮演着至关重要的角色。
字符串在Python中是以Unicode编码的不可变序列。这意味着:
python复制# 字符串创建示例
greeting = "Hello, Python!"
注意:Python没有单独的字符类型,单个字符也是长度为1的字符串
字符串的不可变性带来了一些重要影响:
Python 3默认使用UTF-8编码,这意味着:
python复制# 查看字符串字节表示
name = "张三"
print(name.encode('utf-8')) # b'\xe5\xbc\xa0\xe4\xb8\x89'
Python提供了灵活的字符串创建方式:
python复制s1 = 'single quotes'
s2 = "double quotes"
python复制multi_line = """这是第一行
这是第二行
这是第三行"""
python复制path = r'C:\new_folder\test.txt'
提示:三引号字符串常用于函数文档字符串(docstring)
转义字符让字符串可以包含特殊符号:
| 转义序列 | 含义 | 示例 |
|---|---|---|
| \n | 换行 | "line1\nline2" |
| \t | 制表符 | "Name\tAge" |
| \ | 反斜杠 | "C:\Windows" |
| ' | 单引号 | 'I'm a coder' |
| \uXXXX | Unicode字符 | "\u4e2d"表示"中" |
python复制# 转义字符实际应用
print("Column1\tColumn2\nValue1\tValue2")
字符串支持正向和反向索引:
python复制text = "Python"
# 正向索引 0 1 2 3 4 5
# 反向索引 -6 -5 -4 -3 -2 -1
print(text[0]) # 'P'
print(text[-1]) # 'n'
注意:索引越界会引发IndexError异常
切片语法:[start:stop:step]
python复制s = "abcdefghijk"
print(s[2:5]) # 'cde'
print(s[:5]) # 'abcde'
print(s[3:]) # 'defghijk'
print(s[::2]) # 'acegik'
print(s[::-1]) # 'kjihgfedcba' (反转字符串)
切片特性:
| 方法 | 作用 | 示例 |
|---|---|---|
| upper() | 全部大写 | "hello".upper() → "HELLO" |
| lower() | 全部小写 | "HELLO".lower() → "hello" |
| capitalize() | 首字母大写 | "hello".capitalize() → "Hello" |
| title() | 每个单词首字母大写 | "hello world".title() → "Hello World" |
| swapcase() | 大小写互换 | "Hello".swapcase() → "hELLO" |
python复制# 实际应用场景:用户输入标准化
username = input("用户名: ").strip().lower()
python复制s = "hello world"
print(s.find('l')) # 2 (返回第一个匹配位置)
print(s.find('x')) # -1 (未找到)
print(s.index('l')) # 2
print(s.index('x')) # ValueError异常
python复制text = "I like Java"
new_text = text.replace("Java", "Python")
# 可以指定替换次数
text.replace("a", "o", 1) # 只替换第一个'a'
split()方法的进阶用法:
python复制csv_data = "name,age,gender\nJohn,25,Male"
rows = csv_data.split('\n')
for row in rows:
columns = row.split(',')
print(columns)
join()的高效性体现在:
python复制# 连接大量字符串时务必使用join
words = ['Python'] * 100000
result = ''.join(words) # 高效
python复制"Hello, %s! You have %d messages." % ("Alice", 5)
python复制"Hello, {}! You have {} messages.".format("Alice", 5)
"Hello, {name}! You have {count} messages.".format(name="Alice", count=5)
python复制name = "Alice"
count = 5
f"Hello, {name}! You have {count} messages."
性能测试:f-string > %格式化 > str.format()
python复制num = 1234.5678
print(f"{num:.2f}") # 1234.57
print(f"{num:,}") # 1,234.5678
print(f"{num:.2e}") # 1.23e+03
python复制text = "Python"
print(f"{text:<10}") # 左对齐
print(f"{text:>10}") # 右对齐
print(f"{text:^10}") # 居中对齐
print(f"{text:_^10}") # 用_填充
测试不同拼接方式的性能差异:
python复制from timeit import timeit
def concat_plus():
s = ""
for i in range(1000):
s += str(i)
return s
def concat_join():
return ''.join(str(i) for i in range(1000))
print(timeit(concat_plus, number=1000)) # 约0.15秒
print(timeit(concat_join, number=1000)) # 约0.05秒
结论:
Python会对短字符串和标识符进行驻留(interning)优化:
python复制a = "hello"
b = "hello"
print(a is b) # True (相同对象)
c = "hello world"
d = "hello world"
print(c is d) # Python 3.7+为True
注意:不要依赖驻留机制做业务逻辑判断,应使用==比较内容
python复制user_input = input("请输入: ").strip() # 去除前后空白
if not user_input:
print("输入不能为空")
python复制query = ("SELECT * FROM users "
"WHERE status = 'active' "
"ORDER BY created_at DESC")
python复制password = "secret"
# 使用后立即清除
password = None
python复制# 避免在循环中重复创建相同字符串
TEMPLATE = "Name: {}, Age: {}"
for person in people:
print(TEMPLATE.format(person.name, person.age))
python复制# 字符串转字节
text = "中文"
bytes_data = text.encode('utf-8') # b'\xe4\xb8\xad\xe6\x96\x87'
# 字节转字符串
new_text = bytes_data.decode('utf-8')
常见编码格式:
python复制# 处理未知编码的文本
def safe_decode(byte_data):
for encoding in ['utf-8', 'gbk', 'latin-1']:
try:
return byte_data.decode(encoding)
except UnicodeDecodeError:
continue
return byte_data.decode('utf-8', errors='replace')
python复制log_line = "2023-05-20 14:30:22 [ERROR] Module load failed: FileNotFoundError"
# 提取关键信息
timestamp = log_line[:19]
level = log_line[20:26].strip('[]')
message = log_line[27:]
# 或者使用split
parts = log_line.split(' ', 2)
date, time, rest = parts[0], parts[1], parts[2]
python复制dirty_data = " Price: $1,234.56 "
# 清洗步骤
clean_data = (dirty_data
.strip() # 去空格
.replace('$', '') # 去美元符号
.replace(',', '')) # 去千分位逗号
price = float(clean_data.split(':')[1])
python复制from string import Template
t = Template("""
Dear $name,
Your order #$order_id totaling $$amount has been shipped.
Thanks,
$store_name
""")
email = t.substitute(
name="Alice",
order_id=1001,
amount=99.99,
store_name="Python Shop"
)
python复制# 错误处理
try:
text = byte_data.decode('utf-8')
except UnicodeDecodeError:
text = byte_data.decode('utf-8', errors='replace')
python复制s = "hello"
s.upper() # 不会改变s
s = s.upper() # 正确做法
python复制# 使用f-string避免类型错误
value = 123
print(f"The value is {value}") # 自动转换类型
python复制# 不好
result = ""
for item in items:
result += str(item)
# 好
result = "".join(str(item) for item in items)
python复制# 简单替换
text.replace("old", "new") # 比re.sub快
python复制from string import Template
t = Template("Name: $name, Age: $age")
for person in people:
print(t.substitute(name=person.name, age=person.age))
python复制trans_table = str.maketrans('aeiou', '12345')
text = "This is an example".translate(trans_table)
# 结果: "Th3s 3s 1n 2x1mpl2"
python复制text = "Python"
print(text.ljust(10, '-')) # Python----
print(text.rjust(10, '*')) # ****Python
print(text.center(10, '=')) # ==Python==
| 方法 | 用途 | 示例 |
|---|---|---|
| isalpha() | 是否全为字母 | "abc".isalpha() → True |
| isdigit() | 是否全为数字 | "123".isdigit() → True |
| isalnum() | 是否字母或数字 | "a1".isalnum() → True |
| isspace() | 是否空白字符 | " \t\n".isspace() → True |
| startswith() | 是否以指定字符串开头 | "hello".startswith('he') → True |
| endswith() | 是否以指定字符串结尾 | "world".endswith('ld') → True |
python复制# 实际应用:输入验证
def validate_username(username):
return (len(username) >= 4 and
username.isalnum() and
not username.isdigit())
python复制# 安全转换函数
def str_to_number(s):
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
return None
# 使用示例
num = str_to_number("123.45") # 返回 123.45
python复制# 字符串转列表
chars = list("Python") # ['P', 'y', 't', 'h', 'o', 'n']
# 列表转字符串
words = ['Python', 'is', 'great']
sentence = ' '.join(words) # "Python is great"
python复制# 使用字典进行模板替换
template = "Hello {name}, your balance is {balance:.2f}"
data = {'name': 'Alice', 'balance': 1234.5678}
message = template.format(**data)
python复制# 查找共同字符
s1 = "Python"
s2 = "Programming"
common = set(s1) & set(s2) # {'P', 'o', 'n', 'g', 'r', 'm'}
python复制# 密码处理示例
def process_password(password):
# 处理逻辑...
password = None # 使用后立即清除
在实际项目中,字符串操作往往会占据大量代码。掌握这些技巧不仅能提高代码效率,还能使程序更加健壮和安全。特别是在处理用户输入、文件I/O和网络通信时,正确的字符串处理可以避免许多潜在问题。