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 arr
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
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)
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)
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))
Here is code :
name='india is my country and indians are my brothers and sisters'
vowles='a','e','i','o','u'
for name_1 in name:
if name_1 in vowles:
b=name_1.upper()
print(b,end='')
else:
print(name_1,end='')
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'