1

I want the program to return ' mahir ' as 'MaHiR', I have got MHR but how do I get 'a' and 'h' at their usual place ?

I have already tried slicing but that does not work

s = 'mahir'
a = list (s)
c = a[0:5:2]
for i in range (len(c)):
        print (c[i].capitalize(),end = " ")
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Saturn
  • 27
  • 3

1 Answers1

4

Python's strings are immutable, calling c[i].capitalize() will not change c[i], and therefore will not change s, to modify a string you must create a new one out of it, you can use str.join with a generator expression instead:

s = 'mahir'

s = ''.join(c.upper() if i % 2 == 0 else c for i, c in enumerate(s))

print(s)

Output:

MaHiR

If you want to do it using slicing, you could convert your string to a list since lists are mutable (but the string approach above is better):

s = 'mahir'
l = list(s)
l[::2] = map(str.upper, l[::2])
s = ''.join(l)
print(s)

Output:

MaHiR
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55