Capitalize! Hackerrank problem in Strings section

Question:

I’m trying to solve this problem where you have to capitalize the first and last name entered as input. Following is my code:

def solve(s):


    list1=list(s)
    l1str="".join(list1)
    l1=l1str.split(' ')[0]
    newlist=list(l1)
    newlist[0]=newlist[0].upper()
    partone="".join(newlist)


    l2=l1str.split(' ')[1]
    newlist2= list(l2)
    newlist2[0]=newlist2[0].upper()
    parttwo="".join(newlist2)


    return(partone +" "+ parttwo)

The part which is already provided:

__name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

s = input()

result = solve(s)

fptr.write(result + 'n')

fptr.close()

It does work for any custom case that I enter, and the first test case of Hackerrank as well which was ‘hello world’ but it fails all the other test cases and says that it is because of runtime error. What can I fix?

Asked By: Navdeep singh

||

Answers:

You can do:

def solve(s):
    return " ".join([name.capitalize() for name in s.split(" ")])

explanation

#s.split(" ") and capitalize() then join them using join()

Another detailed approach:

def solve(s):
    answer =""
    l = s.split(" ")
    for i in l:
        if i.isdigit():
            answer += i +" "
        else:
            answer+= i.capitalize()+" "
    return answer.strip()
Answered By: God Is One
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.