更新时间:2022-11-08 21:03:29
您可以使用 str.translate()
方法,让Python一步将其他字符替换为字符.
You can use the str.translate()
method to have Python replace characters by other characters in one step.
使用 string.maketrans()
函数将小写字符映射到大写目标:
Use the string.maketrans()
function to map lowercase characters to their uppercase targets:
try:
# Python 2
from string import maketrans
except ImportError:
# Python 3 made maketrans a static method
maketrans = str.maketrans
vowels = 'aeiouy'
upper_map = maketrans(vowels, vowels.upper())
mystring.translate(upper_map)
这是替换字符串中某些字符的更快,更正确"的方法;您总是可以将mystring.translate()
的结果转换为列表,但是我强烈怀疑您想首先以字符串结尾.
This is the faster and more 'correct' way to replace certain characters in a string; you can always turn the result of mystring.translate()
into a list but I strongly suspect you wanted to end up with a string in the first place.
演示:
>>> try:
... # Python 2
... from string import maketrans
... except ImportError:
... # Python 3 made maketrans a static method
... maketrans = str.maketrans
...
>>> vowels = 'aeiouy'
>>> upper_map = maketrans(vowels, vowels.upper())
>>> mystring = "hello world"
>>> mystring.translate(upper_map)
'hEllO wOrld'