Python字符串处理技巧

1. 字符串基础

字符串是Python中最常用的数据类型之一,用于表示文本数据。在Python中,字符串可以用单引号(')、双引号(")或三引号('''或""")来创建。

# 创建字符串
single_quote = 'Hello World'
double_quote = "Python Programming"
triple_quote = '''这是一个
多行字符串'''

# 访问字符串中的字符
text = "Python"
print(text[0])  # 输出: P
print(text[-1]) # 输出: n

2. 字符串格式化

百分号(%)格式化

name = "Alice"
age = 25
print("姓名: %s, 年龄: %d" % (name, age))

format()方法

print("姓名: {}, 年龄: {}".format(name, age))
print("姓名: {0}, 年龄: {1}".format(name, age))
print("姓名: {n}, 年龄: {a}".format(n=name, a=age))

f-string格式化(Python 3.6+)

print(f"姓名: {name}, 年龄: {age}")
print(f"明年年龄: {age + 1}")

3. 字符串常用方法

大小写转换

text = "Hello Python"
print(text.upper())      # 全大写: HELLO PYTHON
print(text.lower())      # 全小写: hello python
print(text.capitalize()) # 首字母大写: Hello python
print(text.title())      # 每个单词首字母大写: Hello Python
print(text.swapcase())   # 大小写互换: hELLO pYTHON

去除空白字符

text = "   Hello Python   "
print(text.strip())      # 去除两端空白: "Hello Python"
print(text.lstrip())     # 去除左侧空白: "Hello Python   "
print(text.rstrip())     # 去除右侧空白: "   Hello Python"

查找与替换

text = "Hello Python"
print(text.find("Python"))  # 查找子串位置: 6
print(text.replace("Python", "World"))  # 替换子串: "Hello World"
print(text.startswith("Hello"))  # 检查开头: True
print(text.endswith("thon"))    # 检查结尾: True

分割与连接

text = "apple,banana,orange"
fruits = text.split(",")  # 分割字符串: ['apple', 'banana', 'orange']
print(" | ".join(fruits)) # 连接字符串: "apple | banana | orange"

字符串检查

print("123".isdigit())      # 检查是否全为数字: True
print("abc".isalpha())      # 检查是否全为字母: True
print("abc123".isalnum())   # 检查是否为字母和数字: True
print("  ".isspace())       # 检查是否全为空白: True
print("Hello".islower())    # 检查是否全小写: False
print("HELLO".isupper())    # 检查是否全大写: True

4. 字符串高级处理

使用正则表达式处理字符串

import re

text = "My phone number is 123-456-7890"
pattern = r"\d{3}-\d{3}-\d{4}"
match = re.search(pattern, text)
if match:
    print("找到的电话号码:", match.group())  # 输出: 123-456-7890

# 查找所有匹配
emails = "Contact me at user1@example.com or user2@example.org"
email_pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
print(re.findall(email_pattern, emails))  # 输出: ['user1@example.com', 'user2@example.org']

多行字符串处理

multiline = """第一行
第二行
第三行"""
lines = multiline.split("\n")  # 分割为行列表
for i, line in enumerate(lines):
    print(f"行 {i+1}: {line.strip()}")

字符串对齐

text = "Python"
print(text.ljust(20, "-"))  # 左对齐: "Python--------------"
print(text.rjust(20, "-"))  # 右对齐: "--------------Python"
print(text.center(20, "-")) # 居中对齐: "-------Python-------"

5. 字符串性能优化

避免使用+连接大量字符串

# 不推荐 - 效率低
parts = ["Hello", "Python", "World"]
result = ""
for part in parts:
    result += part + " "

# 推荐 - 使用join()
result = " ".join(parts)

使用字符串模板处理复杂格式

from string import Template

template = Template("Hello $name, welcome to $place!")
message = template.substitute(name="Alice", place="Wonderland")
print(message)  # 输出: Hello Alice, welcome to Wonderland!

6. 总结

Python提供了丰富的字符串处理功能,从基本的创建和访问到复杂的正则表达式匹配。掌握这些技巧可以大大提高文本处理的效率。在实际应用中,应根据需求选择合适的方法,并注意性能优化,特别是在处理大量字符串时。通过合理使用f-string、join()方法和正则表达式,可以使代码更简洁高效。字符串处理是Python编程中的基础技能,熟练掌握这些技巧对于数据处理、文本分析和Web开发等任务都至关重要。

发表回复

后才能评论