Python 字符串操作详解
***本文由AI辅助生成***
Python 字符串操作详解
字符串在Python中是不可变的对象,它们支持许多内建的操作,用于格式化、搜索、替换以及分割字符串。以下是一些常见和实用的字符串操作方法:
1. 查找子字符串
使用 in
关键字检查子字符串是否存在,或者使用 find()
和 index()
方法:
text = "Hello, world!"
if "world" in text:
print("Found it!")
position = text.find("world") # 7
print(position) # 输出第一个匹配项的位置
# index() 类似于 find(),但如果没有找到会抛出 ValueError
position = text.index("universe") # 将引发异常
2. 字符串格式化
使用 format()
或 f-string(Python 3.6+)进行格式化,此外也可以使用format_map()
name = "Alice"
age = 30
# format()
print("My name is {} and I am {} years old.".format(name, age))
# f-string
print(f"My name is {
name} and I am {
age} years old.")
# format_map()
mapping = {
"name": "Alice", "age": 30}
print("My name is {name} and I am {age} years old.".format_map(mapping))
3. 字符串分割
split()
:按指定字符,将字符串分割成多份,并放到数组中。
partition()
和 rpartition()
:这两个方法分别从左边或右边查找第一次出现的字符,并返回一个元组包含三部分:前缀、字符本身、后缀。
注:示例中展示的字符为 “-”,也可以使用其他字符或英文字母。
splitlines()
:按换行符,将字符串分割(可处理不同类型的换行符)。
# split()
text = "apple, banana, cherry"
fruits = text.split(", ")
print(fruits) # ['apple', 'banana', 'cherry']
# partition()
text = "hello-world-example"
prefix, sep, suffix = text.partition("-")
print(prefix, sep, suffix) # hello - world-example
# rpartition()
_, _, example = text.rpartition("-")
print(example) # example
# splitlines()
text = "line1\nline2\rline3\r\nline4"
lines = text.splitlines()
print(lines)