文章目录
Python字符串常用方法详解
字符串方法是Python编程中最常用的工具之一,它们就像字符串的"瑞士军刀",能帮你完成各种文本处理任务。下面我将用通俗易懂的方式,结合大量代码示例,详细讲解Python字符串的常用方法。
一、字符串大小写转换方法(常用)
1. 基础大小写转换
| 方法 |
作用 |
示例 |
结果 |
upper() |
全转大写 |
"hello".upper() |
"HELLO" |
lower() |
全转小写 |
"HELLO".lower() |
"hello" |
capitalize() |
首字母大写 |
"hello".capitalize() |
"Hello" |
title() |
每个单词首字母大写 |
"hello world".title() |
"Hello World" |
swapcase() |
大小写互换 |
"PyThOn".swapcase() |
"pYtHoN" |
# 实际应用:用户名规范化
username = "jOhN dOe"
normalized = username.title() # 转为"John Doe"
print(f"欢迎, {normalized}!")
2. 案例:验证码检查(不区分大小写)
user_input = "AbCd"
correct_code = "aBcD"
if user_input.lower() == correct_code.lower():
print("验证码正确")
else:
print("验证码错误")
二、字符串查找与替换方法
1. 查找相关方法
| 方法 |
作用 |
示例 |
结果 |
find(sub) |
查找子串位置 |
"apple".find("p") |
1 |
rfind(sub) |
从右查找子串 |
"apple".rfind("p") |
2 |
index(sub) |
类似find但找不到会报错 |
"apple".index("p") |
1 |
rindex(sub) |
从右查找,找不到报错 |
"apple".rindex("p") |
2 |
count(sub) |
统计出现次数 |
"banana".count("a") |
3 |
# 查找文件扩展名
filename = "report.pdf"
dot_index = filename.rfind(".")
if dot_index != -1:
ext = filename[dot_index+1:]
print(f"文件扩展名: {ext}")
2. 替换相关方法
| 方法 |
作用 |
示例 |
结果 |
replace(old, new) |
替换子串 |
"hello".replace("l", "L") |
"heLLo" |
expandtabs(tabsize) |
替换tab为空格 |
"a\tb".expandtabs(4) |
"a b" |
# 敏感词过滤
text = "这个产品太垃圾了!"
bad_words = ["垃圾", "废物", "差劲"]
for word in bad_words:
text = text.replace(word, "**")
print(text) # 输出: "这个产品太**了!"
三、字符串判断方法
1. 内容判断方法
| 方法 |
作用 |
示例 |
结果 |
startswith(prefix) |
是否以某子串开头 |
"hello".startswith("he") |
True |
endswith(suffix) |
是否以某子串结尾 |
"world".endswith("ld") |
True |
isalnum() |
是否字母或数字 |
"abc123".isalnum() |
True |
isalpha() |
是否全为字母 |
"abc".isalpha() |
True |
isdigit() |
是否全为数字 |
"123".isdigit() |
True |
isnumeric() |
是否数字字符 |
"Ⅷ".isnumeric() |
True |
isdecimal() |
是否十进制数字 |
"12".isdecimal() |
True |
isspace() |
是否全为空白字符 |
" ".isspace() |
True |
islower() |
是否全小写 |
"hello".islower() |
True |
isupper() |
是否全大写 |
"HELLO".isupper() |
True |
istitle() |
是否标题化(首字母大写) |
"Hello".istitle() |
True |
# 密码强度验证
password = "Passw0rd!"
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 = any(not c.isalnum() for c in password)
print(f"密码强度: {has_upper and has_lower and has_digit and has_special}")
四、字符串分割与连接方法(常用)
1. 分割方法
| 方法 |
作用 |
示例 |
结果 |
split(sep) |
按分隔符分割 |
"a,b,c".split(",") |
['a', 'b', 'c'] |
rsplit(sep) |
从右开始分割 |
"a,b,c".rsplit(",", 1) |
['a,b', 'c'] |
splitlines() |
按行分割 |
"第一行\n第二行".splitlines() |
['第一行', '第二行'] |
partition(sep) |
分成三部分 |
"hello.world".partition(".") |
('hello', '.', 'world') |
rpartition(sep) |
从右分成三部分 |
"hello.world.py".rpartition(".") |
('hello.world', '.', 'py') |
# 解析URL参数
url = "https://example.com?name=John&age=25"
_, params = url.split("?", 1) # 分割一次
params_dict = dict(p.split("=") for p in params.split("&"))
print(params_dict) # 输出: {'name': 'John', 'age': '25'}
2. 连接方法
| 方法 |
作用 |
示例 |
结果 |
join(iterable) |
连接字符串序列 |
",".join(["a","b","c"]) |
"a,b,c" |
# 路径拼接
parts = ["C:", "Users", "John", "Documents"]
path = "\\".join(parts) # Windows路径
print(path) # 输出: C:\Users\John\Documents
五、字符串修剪与填充方法
1. 修剪方法
| 方法 |
作用 |
示例 |
结果 |
strip() |
去除两端空白 |
" hi ".strip() |
"hi" |
lstrip() |
去除左端空白 |
" hi ".lstrip() |
"hi " |
rstrip() |
去除右端空白 |
" hi ".rstrip() |
" hi" |
# 清理用户输入
user_input = " admin@example.com "
clean_input = user_input.strip()
print(f"清理后: '{clean_input}'") # 输出: 'admin@example.com'
2. 填充方法
| 方法 |
作用 |
示例 |
结果 |
center(width) |
居中填充 |
"hi".center(10) |
" hi " |
ljust(width) |
左对齐填充 |
"hi".ljust(5) |
"hi " |
rjust(width) |
右对齐填充 |
"hi".rjust(5) |
" hi" |
zfill(width) |
用0填充 |
"42".zfill(5) |
"00042" |
# 生成表格格式
products = [("苹果", 5.5), ("香蕉", 3.2), ("橙子", 4.8)]
for name, price in products:
print(f"{name.ljust(6)}: {str(price).rjust(5)}元")
# 输出:
# 苹果 : 5.5元
# 香蕉 : 3.2元
# 橙子 : 4.8元
六、字符串编码解码方法
1. 编码方法
| 方法 |
作用 |
示例 |
结果 |
encode() |
转为字节序列 |
"你好".encode("utf-8") |
b'\xe4\xbd\xa0\xe5\xa5\xbd' |
2. 解码方法
| 方法 |
作用 |
示例 |
结果 |
decode() |
字节转字符串 |
b'\xe4\xbd\xa0\xe5\xa5\xbd'.decode("utf-8") |
"你好" |
# 处理不同编码的文本
text = "中文测试"
bytes_gbk = text.encode("gbk") # 转为GBK编码
bytes_utf8 = text.encode("utf-8") # 转为UTF-8编码
print(f"GBK编码: {bytes_gbk}")
print(f"UTF-8编码: {bytes_utf8}")
# 解码回字符串
print(bytes_gbk.decode("gbk")) # 输出: 中文测试
七、字符串格式化方法
1. 旧式格式化
# %s 字符串, %d 整数, %f 浮点数
template = "姓名: %s, 年龄: %d, 工资: %.2f"
result = template % ("张三", 30, 8500.5)
print(result) # 输出: 姓名: 张三, 年龄: 30, 工资: 8500.50
# 位置参数
"{}的{}成绩是{}".format("张三", "数学", 95)
# 命名参数
"{name}的{subject}成绩是{score}".format(
name="李四",
subject="英语",
score=88
)
# 数字格式化
"圆周率: {:.2f}".format(3.1415926) # 输出: 圆周率: 3.14
"金额: {:,}".format(1234567) # 输出: 金额: 1,234,567
3. f-string (Python 3.6+)
name = "王五"
age = 25
salary = 12000.5
# 基础用法
f"{name}今年{age}岁"
# 表达式计算
f"明年{name}就{age + 1}岁了"
# 数字格式化
f"工资: {salary:,.2f}元" # 输出: 工资: 12,000.50元
# 对齐
f"姓名: {name:<10} 年龄: {age:>5}" # 左对齐和右对齐
八、实际应用案例
案例1:文本分析工具
def analyze_text(text):
# 统计字符数
char_count = len(text)
# 统计单词数
word_count = len(text.split())
# 统计句子数(简单版)
sentence_count = text.count('.') + text.count('!') + text.count('?')
# 找出最长单词
words = text.replace(',', '').replace('.', '').split()
longest_word = max(words, key=len) if words else ""
return {
"字符数": char_count,
"单词数": word_count,
"句子数": sentence_count,
"最长单词": longest_word
}
result = analyze_text("Hello, world! This is a test.")
print(result)
# 输出: {'字符数': 25, '单词数': 5, '句子数': 2, '最长单词': 'Hello'}
案例2:密码生成器
import random
import string
def generate_password(length=12):
# 定义字符集
lowercase = string.ascii_lowercase
uppercase = string.ascii_uppercase
digits = string.digits
symbols = "!@#$%^&*"
# 确保每种类型至少一个字符
password = [
random.choice(lowercase),
random.choice(uppercase),
random.choice(digits),
random.choice(symbols)
]
# 填充剩余长度
all_chars = lowercase + uppercase + digits + symbols
password.extend(random.choice(all_chars) for _ in range(length - 4))
# 打乱顺序
random.shuffle(password)
return ''.join(password)
print(f"生成密码: {generate_password()}")
# 示例输出: 生成密码: pA7^hK9$m2Lb
九、总结
Python字符串方法核心要点:
- 大小写转换 :
upper(), lower(), title(), capitalize()
- 查找替换 :
find(), index(), count(), replace()
- 内容判断 :
startswith(), isdigit(), isalpha(), isalnum()
- 分割连接 :
split(), join(), partition()
- 修剪填充 :
strip(), ljust(), center(), zfill()
- 格式化 :
format(), f-string
- 编码解码 :
encode(), decode()
掌握这些字符串方法,你就能高效处理各种文本操作任务,从简单的字符串处理到复杂的数据清洗都能游刃有余!