Ravindu Shantha Ravindu Shantha - 11 days ago 7
Python Question

String capitalize with python

Now I Am doing very small question at HackRank about string manipulations it is very easy one just like homework dump . The question is turn a given string to capitalize they mentioned their question just like below

You are given a string . Your task is to capitalize each word of S.

Input Format

A single line of input containing the string, S.

Constraints

0< len(s) <1000


The string consists of alphanumeric characters and spaces.
Output Format

Sample Input

hello world


Sample Output

Hello World


I have done here I wrote a two line script from python and I submitted it but
they said it is a wrong answer but I can't understand why is that my code is follow

l=list(map(str.capitalize,input().strip(' ').split()))
print(' '.join(l))


Can anyone tell me what is wrong with my code
(it fails on test cases 1 / 3 / 4 / 5 with Python 3, so )
?

Answer

If you don't specifiy the separator to str.split(), "any whitespace string is a separator and empty strings are removed from the result." Note that here "whitespace" includes tabs, newlines etc.

The problem is not clearly specified (there's no definition of what "word" means) and we don't know what they use for test cases, but I assume they have a couple string with newlines or such. Anyway: explicitely specifying " " as the separator makes the tests pass:

# Python 2
s = raw_input()
print " ".join(x.capitalize() for x in s.strip().split(" "))

# Python 3
s = input()
print(" ".join(x.capitalize() for x in s.strip().split(" ")))
Comments