简体   繁体   中英

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

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM