问题描述
这是我想做的,但不起作用:
Here is what I want to do but doesn't work:
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"
在我的数组中不是大写的.
"e"
and "o"
are not uppercase in my array.
推荐答案
您可以使用 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'
这篇关于python如何大写字符串中的某些字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!