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.
- Practice
- Python
- Strings
- Capitalize!
- Discussions
Capitalize!
Capitalize!
+ 0 comments Python 3
print(input().title())
will not work because the question is asking to capitalise firse letter of each word keeping in mind that "if it is a letter". Title and Capitalise are different in function as:'abcd'.title()
results in
'Abcd'
but'12abcd'.title()
results in'12Abcd'
. This is not what we want.
We just want to capitalise first letter of each word, not the first occuring letter of a word.
Instead, use this:s = input() for x in s[:].split(): s = s.replace(x, x.capitalize()) print(s)
+ 0 comments Successive spaces can appear in the actual dataset.
+ 0 comments Got full points for this one-liner:
' '.join(map(str.capitalize, string.split(' ')))
+ 0 comments Before reading discussion:
# preserve spacing def cap(string): result = '' word = '' s_count = 0 space = ' ' for c in range(len(string)): if not string[c].isalnum(): # This is a space result += word.capitalize() # append previous word to result word = '' # reset word to empty string s_count += 1 # inc space count else: # space has ended result += space * s_count # add previous space to result s_count = 0 # reset space count word += string[c] # add char to current word result += word.capitalize() # add remaining word at end of loop return result print(cap(input()))
After:
print(' '.join([x.capitalize() for x in input().split(' ')]))
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.
+ 0 comments If you explicitly split on " " successive spaces are 'stored'
Load more conversations
Sort 1482 Discussions, By:
Please Login in order to post a comment