不常用但特别好用的字符串方法—.partitioin()和.translate()
在 Python 中, str.partition()
和 str.translate()
是两种有用的字符串方法,可以帮助您以不同的方式操作字符串。
1. str.partition(sep)
该 partition()
方法使用指定的分隔符 ( sep
) 将字符串拆分为三个部分。它返回一个元组,其中包含:
- 分隔符之前的部分
- 分隔符本身
- 分隔符之后的部分
Example:
s = "hello:world"
part1, sep, part2 = s.partition(":")
print(part1) # Output: "hello"
print(sep) # Output: ":"
print(part2) # Output: "world"
2. str.translate(mapper)
该 translate()
方法使用转换表 ( mapper
) 替换字符串中的指定字符。它返回一个应用了替换项的新字符串。转换表是一个类似字典的对象,它将 Unicode 序数(整数)映射到 Unicode 序数或字符串。您可以使用该 str.maketrans()
函数创建翻译表,该函数采用两个参数:要替换的字符串和替换值的字符串。
Example:
s = "Hello World"
translation_table = str.maketrans("HW", "hh")
new_s = s.translate(translation_table)
print(new_s) # Output: "hello world"
在此示例中,转换表 H
替换为 h
和用 W
替换为w
。
何时使用每种方法
- 当您需要使用特定分隔符将字符串拆分为三个部分时使用
partition()
。 - 当需要替换字符串中的特定字符时使用
translate()
。