字符串是 Python 中最常用的数据类型之一,掌握这些技巧,写代码效率翻倍!
案例 1:字符串反转
题目:输入一个字符串,输出其反转结果。
s = "Python"
# 方法1:切片(最简洁)
print(s[::-1]) # nohtyP
# 方法2:reversed()
print(''.join(reversed(s))) # nohtyP
💡 要点:[::-1] 是 Python 的"神级"切片语法,面试常考。
案例 2:判断回文字符串
题目:判断字符串是否正读反读都相同。
defis_palindrome(s):
# 统一转小写并去除非字母字符
cleaned = ''.join(c.lower() for c in s if c.isalnum())
return cleaned == cleaned[::-1]
print(is_palindrome("A man, a plan, a canal: Panama")) # True
print(is_palindrome("hello")) # False
💡 要点:实际场景中要注意大小写和标点符号的处理。
案例 3:统计字符出现次数
题目:统计字符串中每个字符出现的次数。
from collections import Counter
text = "hello world"
counter = Counter(text)
print(counter)
# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
# 找出出现最多的字符
most_common = counter.most_common(1)
print(most_common) # [('l', 3)]
💡 要点:collections.Counter 是统计利器,比手写字典更优雅。
案例 4:字符串格式化对比
题目:用不同方式拼接用户信息。
name = "张三"
age = 25
score = 95.5
# 方法1:% 格式化(古老,不推荐)
print("姓名:%s,年龄:%d" % (name, age))
# 方法2:str.format()
print("姓名:{},年龄:{}".format(name, age))
# 方法3:f-string(推荐,Python 3.6+)
print(f"姓名:{name},年龄:{age},成绩:{score:.1f}")
# 方法4:模板字符串(安全,防注入)
from string import Template
t = Template("姓名:$name,年龄:$age")
print(t.substitute(name=name, age=age))
💡 要点:f-string 是现在的主流选择,可读性最好。
案例 5:提取字符串中的数字
题目:从混合文本中提取所有数字。
import re
text = "订单号:20240504,价格:¥128.50元,数量:3件"
# 提取所有数字(包括小数)
numbers = re.findall(r'\d+\.?\d*', text)
print(numbers) # ['20240504', '128.50', '3']
# 提取整数
integers = re.findall(r'\d+', text)
print(integers) # ['20240504', '128', '50', '3']
💡 要点:正则表达式是字符串处理的瑞士军刀。
案例 6:多行字符串与文本对齐
题目:生成格式化的表格输出。
data = [
("商品", "价格", "库存"),
("iPhone", "¥5999", "100"),
("MacBook", "¥12999", "50"),
]
for item in data:
print(f"{item[0]:<10}{item[1]:>8}{item[2]:>6}")
# 输出:
# 商品 价格 库存
# iPhone ¥5999 100
# MacBook ¥12999 50
💡 要点:{变量:宽度} 可以控制对齐方式,< 左对齐,> 右对齐,^ 居中。
案例 7:字符串清洗(数据预处理)
题目:清洗用户输入的脏数据。
raw_input = " Hello, World!! How are you??? "
# 去除首尾空格
cleaned = raw_input.strip()
print(cleaned)
# 去除多余空格,统一标点
import re
result = re.sub(r'\s+', ' ', cleaned) # 多个空格变一个
result = re.sub(r'([!?.]){2,}', r'\1', result) # 多个标点变一个
print(result)
# Hello, World! How are you?
💡 要点:数据清洗是数据分析的第一步,strip() 和正则配合无敌。
案例 8:URL 参数解析
题目:解析 URL 中的查询参数。
from urllib.parse import urlparse, parse_qs
url = "https://example.com/search?q=python&page=1&category=programming"
parsed = urlparse(url)
params = parse_qs(parsed.query)
print(f"路径:{parsed.path}") # /search
print(f"参数:{params}")
# {'q': ['python'], 'page': ['1'], 'category': ['programming']}
# 获取单个参数
print(f"搜索词:{params['q'][0]}") # python
💡 要点:不要手动解析 URL,标准库已经帮你做好了。
案例 9:敏感词过滤
题目:将文本中的敏感词替换为 ***。
import re
text = "这个产品真的很棒,垃圾质量,太差了"
sensitive_words = ["垃圾", "差", "笨蛋"]
# 构建正则表达式
pattern = re.compile('|'.join(map(re.escape, sensitive_words)))
result = pattern.sub(lambda m: '*' * len(m.group()), text)
print(result)
# 这个产品真的很棒,**质量,*了
💡 要点:re.escape() 可以避免特殊字符导致正则错误。
案例 10:生成随机验证码
题目:生成包含字母和数字的 6 位验证码。
import random
import string
defgenerate_code(length=6):
chars = string.ascii_letters + string.digits
return''.join(random.choices(chars, k=length))
print(generate_code()) # 如:a3K9pL
print(generate_code(8)) # 如:X7mN2vQ9
💡 要点:random.choices() 允许重复选取,适合验证码场景。
📋 总结速查表
| |
|---|
| s[::-1] |
| |
| collections.Counter |
| re |
| urllib.parse |
| random.choices() |
🎯 练习建议:把上面 10 个案例自己手敲一遍,比看十遍效果都好!