Python字符串常用方法详解

文章目录

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"
python 复制代码
# 实际应用:用户名规范化
username = "jOhN dOe"
normalized = username.title()  # 转为"John Doe"
print(f"欢迎, {normalized}!")

2. 案例:验证码检查(不区分大小写)

python 复制代码
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
python 复制代码
# 查找文件扩展名
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"
python 复制代码
# 敏感词过滤
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
python 复制代码
# 密码强度验证
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')
python 复制代码
# 解析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"
python 复制代码
# 路径拼接
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"
python 复制代码
# 清理用户输入
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"
python 复制代码
# 生成表格格式
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") "你好"
python 复制代码
# 处理不同编码的文本
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. 旧式格式化

python 复制代码
# %s 字符串, %d 整数, %f 浮点数
template = "姓名: %s, 年龄: %d, 工资: %.2f"
result = template % ("张三", 30, 8500.5)
print(result)  # 输出: 姓名: 张三, 年龄: 30, 工资: 8500.50

2. format方法

python 复制代码
# 位置参数
"{}的{}成绩是{}".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+)

python 复制代码
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:文本分析工具

python 复制代码
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:密码生成器

python 复制代码
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字符串方法核心要点:

  1. 大小写转换upper(), lower(), title(), capitalize()
  2. 查找替换find(), index(), count(), replace()
  3. 内容判断startswith(), isdigit(), isalpha(), isalnum()
  4. 分割连接split(), join(), partition()
  5. 修剪填充strip(), ljust(), center(), zfill()
  6. 格式化format(), f-string
  7. 编码解码encode(), decode()

掌握这些字符串方法,你就能高效处理各种文本操作任务,从简单的字符串处理到复杂的数据清洗都能游刃有余!

相关推荐
SelectDB17 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码1 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵1 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
hez20102 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
Lyn_Li2 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸2 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学2 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi3 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化