Home > other >  how to iterate through a string and change a character in it in python
how to iterate through a string and change a character in it in python

Time:12-15

I want to capitalize a char in a string, specifically using a for loop. Can someone show how this is done using the code below. or something simpler but still using for loop iterations

name = input("Enter name")   
name_list = list(name)

for i in range(len(name_list)):

    if i == name_list[3]:
        name_list = name_list[3].upper

    else:
        name_list  = i

print(name_list)

CodePudding user response:

Assuming this is Python, you can it by assigning the newly uppercase letter to the list at the lowercase letter's index. For example, if we want to make every third letter upper case in the string enter name, then:

name = "enter name"
name_list = list(name)

for i in range(len(name_list)):
    if i % 3 == 0:
        name_list[i] = name_list[i].upper()
        
print(''.join(name_list))

Output:

EntEr NamE
  • Related