python如何在字符串中大写一些字符

Bou*_*TAC 2 python string list uppercase

这是我想要做但不起作用的:

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) 
Run Code Online (Sandbox Code Playgroud)

"e"并且"o"在我的数组中不是大写的.

Mar*_*ers 8

您可以使用该str.translate()方法让Python在一个步骤中替换其他字符.

使用该string.maketrans()函数将小写字符映射到其大写目标:

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)
Run Code Online (Sandbox Code Playgroud)

这是替换字符串中某些字符的更快,更"正确"的方法; 你总是可以把结果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'
Run Code Online (Sandbox Code Playgroud)


Bha*_*Rao 5

您没有对原始列表进行更改.您只对循环变量进行更改c.作为一种解决方法,您可以尝试使用enumerate.

mystring = "hello world"
toUpper = ['a', 'e', 'i', 'o', 'u', 'y']
array = list(mystring)

for i,c in enumerate(array):
    if c in toUpper:
        array[i] = c.upper()

print(array) 
Run Code Online (Sandbox Code Playgroud)

产量

['h', 'E', 'l', 'l', 'O', ' ', 'w', 'O', 'r', 'l', 'd']
Run Code Online (Sandbox Code Playgroud)

注意:如果你想要hEllO wOrld的答案,你还不如用join''.join(array)


归档时间:

查看次数:

4805 次

最近记录:

7 年,3 月 前