[Python] Python function to capitalize the first letter of every word in an input sentence...

Discussão em 'Python' iniciado por Stack, Agosto 31, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to beat a hacker rank Python problem where am given an input string comprising of words separated by space

    alex mcqueen
    timothy karl logan


    I am required to capitalize the first letter of each word and then return the modified string

    I tried this Python function

    def solve(s):
    ret = ""
    words = s.split(" ")
    capitalized = []
    for word in words:
    first = word[0].upper() # capitalize the first character
    ret += first # add it to our string
    for i in range(1,len(word)):
    ret += str(word)

    # get the number of words in the sentence for space insertion
    # if the words are three then you need two spaces(N-1)
    cnt = len(words)
    idx = 0
    y = ""
    # loop through checking for uppers and insert a space
    for i in range(len(ret)):
    if ret.isupper() and idx != cnt:
    y+= " " # add a space and then increment index
    y+=ret
    idx+=1
    elif ret.islower():
    y += ret

    return y



    It is giving me the right output but somehow its adding extra space(s) at the end of the concatenated word

    Continue reading...

Compartilhe esta Página