这是我想做的,但是不起作用:
mystring = "hello world"
toUpper = ['a', 'e', 'i', 'o', 'u', 'y']
array = list(mystring)
for c in array:
if c in toUpper:
c = c.upper()
print(array)
我的数组中“ e”和“ o”不是大写.
解决方法:
您可以使用str.translate()
method一步使Python用其他字符替换字符.
使用string.maketrans()
function将小写字符映射到其大写目标:
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()的结果转换为列表,但我强烈怀疑您首先要以字符串结尾.
演示:
>>> 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'