-1

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 ) ?

  • Please peoples **READ THE QUESTION !** The op is not asking for "how to" nor "a better way", he's asking **why** his code fails the tests on HackRank ! – bruno desthuilliers Nov 21 '16 at 15:01

3 Answers3

1

Use str.title

>>>'aba aba'.title()
'Aba Aba'
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
0

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(" ")))
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • Thank you lot sir .finally my code also worked .Thank you sir!! `l=list(map(str.capitalize,input().strip(' ').split(' '))) print(' '.join(l))` – Ravindu De Silva Nov 21 '16 at 15:29
  • Now that you know why your code failed, you may want to read up Patrick Haugh's answer... which while not answering your question is still the pythonic way to capitalize all words in a string. – bruno desthuilliers Nov 22 '16 at 13:04
-1

I presume the error is on input(). If HackRank is using python 2.7, this will try to evaluate the input, rather than returning a string. Thus, an input hello world will try to evaluate this string, which is nonsense. If you try raw_input() in stead, this should fix this problem.

Lolgast
  • 329
  • 2
  • 10