Sort 1593 Discussions, By:
Please Login in order to post a comment
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:
results in 'Abcd'
s = input()
for x in s[:].split():
s = s.replace(x, x.capitalize())
Successive spaces can appear in the actual dataset.
Got full points for this one-liner:
' '.join(map(str.capitalize, string.split(' ')))
Before reading discussion:
# preserve spacing
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
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.
If you explicitly split on " " successive spaces are 'stored'