We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
# preserve spacingdefcap(string):result=''word=''s_count=0space=' 'forcinrange(len(string)):ifnotstring[c].isalnum():# This is a spaceresult+=word.capitalize()# append previous word to resultword=''# reset word to empty strings_count+=1# inc space countelse:# space has endedresult+=space*s_count# add previous space to results_count=0# reset space countword+=string[c]# add char to current word result+=word.capitalize()# add remaining word at end of loopreturnresultprint(cap(input()))
Note that using the capitalize method helps with the strings that begin with numbers and should be skipped. Explicit splitting with a ' ' preserves adjacent spaces. Neato.
Doing things the naive way definitely helps you appreciate the elegant.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Capitalize!
You are viewing a single comment's thread. Return to all comments →
Before reading discussion:
After:
Note that using the capitalize method helps with the strings that begin with numbers and should be skipped. Explicit splitting with a
' '
preserves adjacent spaces. Neato.Doing things the naive way definitely helps you appreciate the elegant.