Python 字符串操作详解
Python 字符串(str)是不可变的序列类型,用于存储和操作文本。以下是 Python 中常见的字符串操作,包括连接、切片、格式化,以及常用的字符串方法和正则表达式的使用。
1. 字符串连接
使用 + 操作符:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # 输出: "Hello World"
使用 join() 方法:
words = ["Hello", "World"]
result = " ".join(words)
print(result) # 输出: "Hello World"
2. 字符串切片
text = "Hello World"
# 切片从索引 0 到 4(不包括 5)
print(text[0:5]) # 输出: "Hello"
# 从索引 6 开始到末尾
print(text[6:]) # 输出: "World"
# 反向切片
print(text[-5:]) # 输出: "World"
# 步长切片(每隔一个字符)
print(text[::2]) # 输出: "HloWrd"
3. 字符串格式化
使用 % 操作符:
name = "Alice"
age = 30
text = "Name: %s, Age: %d" % (name, age)
print(text) # 输出: "Name: Alice, Age: 30"
使用 str.format() 方法:
text = "Name: {}, Age: {}".format(name, age)
print(text) # 输出: "Name: Alice, Age: 30"
使用 f-string (Python 3.6+):
text = f"Name: {name}, Age: {age}"
print(text) # 输出: "Name: Alice, Age: 30"
4. 字符串常用方法
-
split(): 按指定分隔符拆分字符串text = "apple,banana,cherry" fruits = text.split(",") print(fruits) # 输出: ['apple', 'banana', 'cherry'] -
join(): 用指定分隔符连接列表中的字符串fruits = ['apple', 'banana', 'cherry'] result = ", ".join(fruits) print(result) # 输出: "apple, banana, cherry" -
replace(): 替换字符串中的某部分text = "Hello World" result = text.replace("World", "Python") print(result) # 输出: "Hello Python" -
find()和index(): 查找子字符串的位置text = "Hello World" pos = text.find("World") # 返回 6 pos = text.index("World") # 返回 6,如果未找到则抛出异常 -
strip(): 去除字符串首尾的空白字符(lstrip()去除左侧空白,rstrip()去除右侧空白)text = " Hello World " result = text.strip() # 输出: "Hello World" -
upper()和lower(): 转换为全大写或全小写text = "Hello World" print(text.upper()) # 输出: "HELLO WORLD" print(text.lower()) # 输出: "hello world" -
startswith()和endswith(): 判断字符串是否以特定前缀或后缀开头/结尾text = "Hello World" print(text.startswith("Hello")) # 输出: True print(text.endswith("World")) # 输出: True
5. 正则表达式操作
Python 的 re 模块提供了正则表达式功能。
-
匹配正则表达式:
re.match()import re pattern = r"^Hello" text = "Hello World" match = re.match(pattern, text) if match: print("Match found") # 输出: "Match found" -
搜索正则表达式:
re.search()match = re.search(r"World$", text) if match: print("Match found") # 输出: "Match found" -
替换:
re.sub()result = re.sub(r"World", "Python", text) print(result) # 输出: "Hello Python" -
查找所有:
re.findall()text = "apple, banana, cherry" fruits = re.findall(r"\b\w+\b", text) print(fruits) # 输出: ['apple', 'banana', 'cherry'] -
编译正则表达式:
re.compile()pattern = re.compile(r"^Hello") match = pattern.match(text) if match: print("Match found") # 输出: "Match found"
6. 其他常用字符串方法
-
capitalize(): 将字符串的第一个字符转换为大写。text = "hello world" print(text.capitalize()) # 输出: "Hello world" -
title(): 将字符串的每个单词的首字母转换为大写。text = "hello world" print(text.title()) # 输出: "Hello World" -
count(): 返回子字符串在字符串中出现的次数。text = "banana" print(text.count("a")) # 输出: 3 -
isalnum(): 判断字符串是否只包含字母和数字。text = "hello123" print(text.isalnum()) # 输出: True -
isalpha(): 判断字符串是否只包含字母。text = "hello" print(text.isalpha()) # 输出: True -
isdigit(): 判断字符串是否只包含数字。text = "12345" print(text.isdigit()) # 输出: True -
isspace(): 判断字符串是否只包含空白字符。text = " " print(text.isspace()) # 输出: True
总结
掌握 Python 中的字符串操作和正则表达式可以大大提高你的文本处理能力。了解如何切片、格式化、查找、替换字符串,并熟练使用正则表达式将使你在数据清洗、文本解析等任务中更加得心应手。