Home > Net >  Improving Code: Capitalizing the first and third letter of a string
Improving Code: Capitalizing the first and third letter of a string

Time:03-30

This is the first time I am learning python. I have had two C programming classes during my undergraduate days (many years back). I usually understand basic algorithms, but struggle to write codes out.

Currently doing a course in UDEMY, and the problem requires us to capitalize the first and third letters of the string. I have written the code (took me a while) and it works, but I know it is not pretty.

Please note: Trying to code it without using the enumerate function.

def wordplay(text):

    first = text[0:1]                                             #isolate the first letter
    third = text[2:3]                                             #isolate the third letter
    
    firstc = first.capitalize()                                   #capitalize the first letter
    thirdc = third.capitalize()                                   #capitalize the third letter
    changedword = firstc   text[1:2]   thirdc   text[3:]          #change the first and third letter to capital in the string
    
    print(changedword)

The code worked, but looking to improve my logic (without using enumerate)

CodePudding user response:

Here is one option which uses the capitalize() function:

inp = "hello"
output = inp[0:2].capitalize()   inp[2:].capitalize()
print(output)  # HeLlo

The idea here is to just capitalize two substrings, one for the first two letters and the other for the remainder of the string.

  • Related