Search code examples
pythonlettercapitalize

Capitalize letter after exclamation mark


I have string that needs to be capitalized after "!":

I have made a script that works to a certain extent but gives me a problem when the last letter is "!".

strin "hello! there!" 

strout = []

for i in range(len(strin)):     
    if strin[i-2] == '!':
        strout.append((strin[i]).capitalize())

    else:
        strout.append(strin[i])
    strout[0] = strout[0].capitalize()

newStr = "".join(strout)

Output is: HEllo! There!


What can I do to prevent the second letter to be capitalized.
The reason for [i-2] is whenever the loop encounters a '!' in the middle of text it capitalizes the letter i.


Solution

  • a simple solution would be to capitalize only if i-2 >= 0.

    try this:

    strin = "hello! there!"
    
    strout = []
    
    for i in range(len(strin)):
        if i-2>=0 and strin[i-2] == '!':
            strout.append((strin[i]).capitalize())
        else:
            strout.append(strin[i])
    strout[0] = strout[0].capitalize()
    
    newStr = "".join(strout)
    
    print(newStr)