python how to uppercase some characters in string

2019-02-27 12:25发布

问题:

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" and "o" are not uppercase in my array.

回答1:

You can use the str.translate() method to have Python replace characters by other characters in one step.

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)

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.

Demo:

>>> 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'


回答2:

You are not making changes to the original list. You are making changes only to the loop variable c. As a workaround you can try using 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) 

Output

['h', 'E', 'l', 'l', 'O', ' ', 'w', 'O', 'r', 'l', 'd']

Note: If you want hEllO wOrld as the answer, you might as well use join as in ''.join(array)



回答3:

You can do:

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

>>> ''.join([c.upper() if c in toUpper else c for c in mystring])
hEllO wOrld


回答4:

The problem is that al c is not used for anything, this is not passing by reference.

I would do so, for beginners:

mystring = "hello world"
toUpper = ['a', 'e', 'i', 'o', 'u', 'y']
array = []
for c in mystring:
    if c in toUpper:
        c = c.upper()
    array.append(c)
print(''.join(array))


回答5:

Use generator expression like so:

newstring = ''.join(c.upper() if c in toUpper else c for c in mystring)


回答6:

This will do the job. Keep in mind that strings are immutable, so you'll need to do some variation on building new strings to get this to work.

myString = "hello world"
toUpper = ['a', 'e', 'i', 'o', 'u', 'y']
newString = reduce(lambda s, l: s.replace(l, l.upper()), toUpper, myString)


回答7:

Please try this one

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

array = list(mystring)
new_string = [x.upper() if x in toUpper else x for x in array ]



new_string = ''.join(new_string)
print new_string