1. Python字符串基础快速复习指南
作为Python中最常用的数据类型之一,字符串处理是每个Python开发者必须掌握的核心技能。无论你是刚入门的新手还是需要快速回顾的老手,这份指南将带你系统梳理Python字符串的关键知识点和实用技巧。
字符串在Python中是不可变的序列类型,用于表示文本数据。与其他语言相比,Python的字符串处理功能极为强大且语法优雅。从基础的创建、访问到高级的格式化、编码转换,Python提供了一整套完整的字符串操作方法。
提示:Python3中所有字符串默认采用Unicode编码,这解决了Python2时代令人头疼的编码问题,使得多语言文本处理变得更加简单可靠。
1.1 字符串创建与基本操作
Python中创建字符串最简单的方式是使用单引号(')或双引号(")包裹文本内容:
python复制# 三种等价的字符串创建方式
str1 = 'Hello World'
str2 = "Hello World"
str3 = '''Hello World'''
对于多行字符串,可以使用三引号('''或"""):
python复制multi_line = """这是第一行
这是第二行
这是第三行"""
字符串支持基本的序列操作:
- 索引访问:
s[0]获取第一个字符 - 切片操作:
s[1:5]获取第2到第5个字符 - 长度获取:
len(s)返回字符串长度 - 连接操作:
s1 + s2拼接两个字符串 - 重复操作:
s * 3重复字符串3次
python复制s = "Python"
print(s[0]) # 输出 'P'
print(s[1:4]) # 输出 'yth'
print(len(s)) # 输出 6
print(s + "3") # 输出 'Python3'
print(s * 2) # 输出 'PythonPython'
1.2 常用字符串方法
Python为字符串对象提供了丰富的方法,下面分类介绍最常用的几类:
1.2.1 大小写转换
python复制s = "Python String"
print(s.lower()) # 'python string' - 全部小写
print(s.upper()) # 'PYTHON STRING' - 全部大写
print(s.capitalize()) # 'Python string' - 首字母大写
print(s.title()) # 'Python String' - 每个单词首字母大写
print(s.swapcase()) # 'pYTHON sTRING' - 大小写互换
1.2.2 查找与替换
python复制s = "Python is great, Python is powerful"
print(s.find('Python')) # 0 - 返回第一次出现的索引
print(s.rfind('Python')) # 17 - 返回最后一次出现的索引
print(s.index('great')) # 10 - 类似find但找不到会抛出异常
print(s.count('Python')) # 2 - 统计出现次数
print(s.replace('Python', 'Java')) # 替换所有匹配项
注意:find()和index()的区别在于找不到子串时的行为,find()返回-1,index()抛出ValueError异常。
1.2.3 分割与连接
python复制csv = "apple,banana,orange"
print(csv.split(',')) # ['apple', 'banana', 'orange']
lines = "line1\nline2\nline3"
print(lines.splitlines()) # ['line1', 'line2', 'line3']
words = ['Python', 'is', 'awesome']
print(' '.join(words)) # 'Python is awesome'
1.2.4 判断类方法
python复制print("123".isdigit()) # True - 是否全为数字
print("abc".isalpha()) # True - 是否全为字母
print("abc123".isalnum()) # True - 是否只包含字母和数字
print(" ".isspace()) # True - 是否全为空白字符
print("Python".startswith('Py')) # True
print("Python".endswith('on')) # True
1.3 字符串格式化
Python提供了多种字符串格式化方式,各有优缺点:
1.3.1 %格式化(传统方式)
python复制name = "Alice"
age = 25
print("My name is %s and I'm %d years old." % (name, age))
1.3.2 str.format()方法
python复制print("My name is {} and I'm {} years old.".format(name, age))
print("My name is {0} and I'm {1} years old. {0} again!".format(name, age))
print("My name is {n} and I'm {a} years old.".format(n=name, a=age))
1.3.3 f-strings(Python 3.6+推荐)
python复制print(f"My name is {name} and I'm {age} years old.")
print(f"Next year I'll be {age + 1} years old.")
f-string是性能最好也最直观的格式化方式,支持在字符串内直接嵌入表达式。
1.4 字符串编码与字节串
Python3严格区分字符串(str)和字节串(bytes):
python复制s = "中文"
b = s.encode('utf-8') # 字符串转字节串
print(b) # b'\xe4\xb8\xad\xe6\x96\x87'
s2 = b.decode('utf-8') # 字节串转字符串
print(s2) # '中文'
常见的编码格式包括:
- UTF-8:Web应用首选,兼容ASCII
- GBK:中文Windows系统默认编码
- ASCII:仅支持基本英文字符
重要:处理文件或网络数据时,务必注意编码问题。最佳实践是在代码开头统一声明编码(# -- coding: utf-8 --),并在所有IO操作中明确指定编码参数。
1.5 实用字符串技巧
1.5.1 反转字符串
python复制s = "Python"
print(s[::-1]) # 'nohtyP'
1.5.2 去除空白字符
python复制s = " Python "
print(s.strip()) # 'Python' - 去除两端空白
print(s.lstrip()) # 'Python ' - 去除左端空白
print(s.rstrip()) # ' Python' - 去除右端空白
1.5.3 字符串对齐
python复制s = "Python"
print(s.ljust(10, '-')) # 'Python----'
print(s.rjust(10, '-')) # '----Python'
print(s.center(10, '-')) # '--Python--'
1.5.4 字符串与列表转换
python复制# 字符串转字符列表
s = "Python"
char_list = list(s) # ['P', 'y', 't', 'h', 'o', 'n']
# 列表转字符串
print(''.join(char_list)) # 'Python'
1.6 正则表达式基础
对于复杂的字符串匹配和处理,正则表达式是强大工具:
python复制import re
# 匹配数字
text = "Python 3.9 was released in 2020"
print(re.findall(r'\d+', text)) # ['3', '9', '2020']
# 替换操作
print(re.sub(r'\d+', 'X', text)) # 'Python X.X was released in X'
# 分割字符串
print(re.split(r'\W+', text)) # ['Python', '3', '9', 'was', 'released', 'in', '2020']
常用正则元字符:
\d:数字\w:单词字符(字母、数字、下划线)\s:空白字符.:任意字符(除换行符)*:0次或多次+:1次或多次?:0次或1次
1.7 性能考虑与最佳实践
-
字符串拼接:避免在循环中使用
+拼接字符串,因为字符串是不可变对象,每次拼接都会创建新对象。推荐使用join()方法或格式化字符串。python复制# 不推荐 result = "" for s in list_of_strings: result += s # 推荐 result = "".join(list_of_strings) -
字符串驻留:Python会对短字符串和标识符进行驻留(intern)优化,相同的字符串可能会引用同一内存对象。
python复制a = "hello" b = "hello" print(a is b) # True(短字符串) c = "hello world" d = "hello world" print(c is d) # False(长字符串不一定) -
原始字符串:处理正则表达式或Windows路径时,使用原始字符串(前缀r)可以避免转义字符的问题。
python复制path = r"C:\new_folder\test.txt" regex = r"\d+\.\d+" -
字符串缓存:频繁使用的字符串可以考虑缓存起来,避免重复创建。
1.8 常见问题与解决方案
问题1:如何判断字符串是否为空?
python复制s = ""
# 正确方式
if not s:
print("Empty string")
# 或者
if len(s) == 0:
print("Empty string")
# 错误方式(s可能是None)
if s == "":
print("Empty string")
问题2:如何安全地处理可能为None的字符串?
python复制s = None
safe_s = s or "" # 如果s为None,使用空字符串替代
print(safe_s.upper()) # 不会抛出异常
问题3:如何高效地处理大文本文件?
python复制# 逐行处理大文件
with open('large_file.txt', 'r', encoding='utf-8') as f:
for line in f:
process(line) # 处理每一行
# 避免一次性读取整个文件
# 不推荐:content = f.read()
问题4:如何实现字符串的加密/解密?
Python标准库中的hashlib模块可用于哈希计算,cryptography库则提供更强大的加密功能:
python复制import hashlib
# 简单的MD5哈希
s = "secret"
hash_obj = hashlib.md5(s.encode('utf-8'))
print(hash_obj.hexdigest())
问题5:如何处理用户输入中的特殊字符?
python复制import html
user_input = '<script>alert("XSS")</script>'
safe_input = html.escape(user_input)
print(safe_input) # <script>alert("XSS")</script>
1.9 字符串应用实例
1.9.1 日志消息格式化
python复制import datetime
def format_log(level, message):
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return f"[{timestamp}] [{level.upper()}] {message}"
print(format_log("info", "System started"))
# 输出示例:[2023-08-20 14:30:00] [INFO] System started
1.9.2 简单的模板引擎
python复制def render_template(template, context):
for key, value in context.items():
template = template.replace(f"{{{{ {key} }}}}", str(value))
return template
template = "Hello, {name}! Your score is {score}."
context = {"name": "Alice", "score": 95}
print(render_template(template, context))
# 输出:Hello, Alice! Your score is 95.
1.9.3 命令行进度条
python复制import time
def show_progress(iterable, prefix="", length=50):
total = len(iterable)
start_time = time.time()
for i, item in enumerate(iterable):
percent = (i + 1) / total
filled = int(length * percent)
bar = "█" * filled + "-" * (length - filled)
elapsed = time.time() - start_time
print(f"\r{prefix} |{bar}| {percent:.0%} ({i+1}/{total}) [{elapsed:.1f}s]", end="")
yield item
print()
# 使用示例
for _ in show_progress(range(100), "Processing"):
time.sleep(0.05)
1.10 进阶话题
1.10.1 字符串的intern机制
Python会对某些字符串进行驻留(intern)优化,相同的字符串会引用同一内存对象:
python复制a = "hello"
b = "hello"
print(a is b) # True
c = "hello world"
d = "hello world"
print(c is d) # Python 3.7+为True,之前版本可能为False
可以手动使用sys.intern()函数来优化大量重复字符串的内存使用:
python复制import sys
s1 = sys.intern("a long string that appears many times")
s2 = sys.intern("a long string that appears many times")
print(s1 is s2) # True
1.10.2 字符串视图(memoryview)
对于字节串,可以使用memoryview来创建零拷贝的视图:
python复制data = b"Python"
mv = memoryview(data)
slice_mv = mv[2:4]
print(bytes(slice_mv)) # b'th'
1.10.3 自定义字符串格式化
可以通过实现__format__方法来自定义类的字符串格式化行为:
python复制class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __format__(self, format_spec):
if format_spec == "polar":
import math
r = math.hypot(self.x, self.y)
theta = math.atan2(self.y, self.x)
return f"r={r:.2f}, θ={theta:.2f}"
return f"({self.x}, {self.y})"
p = Point(3, 4)
print(f"Cartesian: {p}") # Cartesian: (3, 4)
print(f"Polar: {p:polar}") # Polar: r=5.00, θ=0.93
1.10.4 字符串性能优化技巧
-
使用生成器表达式代替列表推导式处理大字符串:
python复制# 更高效 large_text = "a" * 1000000 upper_chars = "".join(c.upper() for c in large_text) # 较低效(先创建临时列表) upper_chars = "".join([c.upper() for c in large_text]) -
预编译正则表达式用于重复使用:
python复制import re # 预编译 pattern = re.compile(r'\d+') # 多次使用 result1 = pattern.findall(text1) result2 = pattern.findall(text2) -
使用str.maketrans()进行高效的字符替换:
python复制trans_table = str.maketrans("aeiou", "12345") text = "This is an example".translate(trans_table) print(text) # Th3s 3s 1n 2x1mpl2
1.11 字符串与其他数据类型的转换
在实际开发中,经常需要在字符串和其他数据类型之间转换:
1.11.1 数字与字符串
python复制# 字符串转数字
num = int("42") # 42
float_num = float("3.14") # 3.14
# 数字转字符串
s = str(42) # '42'
format_s = f"{3.1415926:.2f}" # '3.14'
1.11.2 列表/元组与字符串
python复制# 列表转字符串
lst = ['a', 'b', 'c']
print(','.join(lst)) # 'a,b,c'
# 字符串转列表
s = "a,b,c"
print(s.split(',')) # ['a', 'b', 'c']
1.11.3 字典与字符串
python复制# 字典转字符串
d = {'name': 'Alice', 'age': 25}
print(str(d)) # "{'name': 'Alice', 'age': 25}"
# JSON字符串与字典转换
import json
json_str = json.dumps(d) # '{"name": "Alice", "age": 25}'
new_d = json.loads(json_str)
1.11.4 字节与字符串
python复制# 字符串转字节
s = "Python"
b = s.encode('utf-8') # b'Python'
# 字节转字符串
s2 = b.decode('utf-8') # 'Python'
1.12 字符串处理实战案例
1.12.1 密码强度检查器
python复制import re
def check_password_strength(password):
if len(password) < 8:
return "Weak: Password too short"
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
has_special = bool(re.search(r'[!@#$%^&*(),.?":{}|<>]', password))
strength = 0
if has_upper: strength += 1
if has_lower: strength += 1
if has_digit: strength += 1
if has_special: strength += 1
if strength == 1: return "Very Weak"
if strength == 2: return "Weak"
if strength == 3: return "Moderate"
return "Strong"
print(check_password_strength("Python3!")) # Strong
1.12.2 简单的文本分析工具
python复制def analyze_text(text):
words = text.split()
word_count = len(words)
char_count = len(text)
line_count = text.count('\n') + 1 if text else 0
avg_word_length = sum(len(word) for word in words) / word_count if word_count else 0
return {
'word_count': word_count,
'char_count': char_count,
'line_count': line_count,
'avg_word_length': avg_word_length,
'unique_words': len(set(words))
}
text = """Python is an interpreted, high-level and general-purpose programming language.
Python's design philosophy emphasizes code readability with its notable use of significant whitespace."""
print(analyze_text(text))
1.12.3 URL参数解析器
python复制def parse_url_params(url):
from urllib.parse import urlparse, parse_qs
parsed = urlparse(url)
params = parse_qs(parsed.query)
return {k: v[0] if len(v) == 1 else v for k, v in params.items()}
url = "https://example.com/search?q=python&page=2&lang=en"
print(parse_url_params(url))
# {'q': 'python', 'page': '2', 'lang': 'en'}
1.13 字符串处理的最佳实践总结
-
优先使用f-string:Python 3.6+中,f-string是最简洁高效的字符串格式化方式。
-
处理路径使用pathlib:虽然字符串可以处理路径,但pathlib.Path更安全可靠。
python复制from pathlib import Path p = Path('dir') / 'file.txt' # 比字符串拼接更安全 -
正则表达式复杂时添加注释:使用re.VERBOSE标志使正则更易读:
python复制pattern = re.compile(r""" \b # 单词边界 \d{3} # 3位数字 - # 连字符 \d{2} # 2位数字 - # 连字符 \d{4} # 4位数字 \b # 单词边界 """, re.VERBOSE) -
处理用户输入要谨慎:总是验证和清理用户提供的字符串,防止注入攻击。
-
大文本处理使用生成器:避免一次性加载大文本到内存,使用逐行处理或生成器。
-
了解字符串不可变性:记住字符串操作总是返回新字符串,原字符串不变。
-
编码问题早发现:在项目初期就确定统一的编码方案(推荐UTF-8),并在所有IO操作中明确指定。
-
性能关键路径优化:对于大量字符串处理,考虑使用内置方法、生成器或第三方库如numpy/pandas。
字符串处理是Python编程的基础,掌握这些核心概念和技巧将显著提升你的开发效率和代码质量。在实际项目中,根据具体需求选择合适的方法,并始终考虑代码的可读性和可维护性。
