12

I'm trying to learn python through HackerRank, and I've been stuck on reading stdin. The problem gives an array of integers as a single line of text formatted like:

1 2 3 4 5

This should become the array:

[1,2,3,4,5].

Since there are spaces in between the numerals in the input, how can I get to an array? I've tried split() and map(), but I kept getting errors or an array that still had spaces.

Thank you!

5
  • I apologize if this is too basic -- I've spent an hour on this and I'm stuck... Commented Dec 1, 2014 at 5:15
  • 1
    I'm pretty sure the downvote doesn't come from the "basic"-ness of the question but of not showing some effort with what you've done. Some code? Why split doesn't work? What made you think that map would work? A particular error you're getting? That kind of stuff... Commented Dec 1, 2014 at 5:16
  • list(map(int, "1 2 3 4 5".split())) Commented Dec 1, 2014 at 5:17
  • @BorrajaX I'll be sure to do that in the future -- thank you for your help Commented Dec 1, 2014 at 5:22
  • @BorrajaX Got it! it made me wait a few minutes before choosing a best answer. Commented Dec 1, 2014 at 5:30

2 Answers 2

20
list(map(int, "1 2 3 4 5".split(" ")))
Sign up to request clarification or add additional context in comments.

1 Comment

>>> map(int, "1 2 3 4 5".split(" ")) <map object at 0x7f4b2489bc90>
12

This list comprehension works equally well on Python2 and Python3

[int(x) for x in "1 2 3 4 5".split()]

str.split() when given no parameters will split on any whitespace

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.