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.
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: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:
The problem is that al
c
is not used for anything, this is not passing by reference.I would do so, for beginners:
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.
Use generator expression like so:
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 usingenumerate
.Output
Note: If you want
hEllO wOrld
as the answer, you might as well usejoin
as in''.join(array)
You can do: