0

I want to capitalise every 5th letter of name

Note: i only want to use .upper() method "not capitalize()"

I tried this but im getting IndexError: string index out of range

name = "Cristiano Ronaldo"

for t in range(0,len(name),5):
    name = str(name)[t].upper()
    print(name)
Sahith Kurapati
  • 1,617
  • 10
  • 14
Marzia Calloo
  • 71
  • 1
  • 6
  • 3
    You are changing `name` to be a single letter... Don't you see that after the first `print`? – Tomerikoo Jun 09 '20 at 12:00
  • 1
    Does this answer your question? [Capitalise every other letter in a string in Python?](https://stackoverflow.com/questions/17865563/capitalise-every-other-letter-in-a-string-in-python) – Tomerikoo Jun 09 '20 at 12:01

4 Answers4

3
"".join([char.upper() if index > 0 and (index - 1) % 5 == 0 else char for index, char in enumerate(name)])
0

you can first change the str to list:

l_name = list(name)

for i in range(0,len(l_name),5):
    l_name[i] = l_name[i].upper()

result = ''.join(l_name)
one
  • 2,205
  • 1
  • 15
  • 37
0

name = "Cristiano Ronaldo"

print(''.join([ letter.upper() if (index+1) % 5 == 0 else letter for index,letter in enumerate(name)]))

enumerate method used to track the index of each letter in string while looping and for every multiple of 5 we are doing letter.upper() else letter

Abhishek-Saini
  • 733
  • 7
  • 11
0

Use pythonic way:

name = "cristiano Ronaldo"
print(''.join([l if i%5 else l.upper() for i, l in enumerate(name, 1)]))
Zain Arshad
  • 1,885
  • 1
  • 11
  • 26