Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a single line string to integer array in Python

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!

like image 579
Will R Avatar asked Dec 01 '14 05:12

Will R


People also ask

How do you convert a string to an int array in Python?

In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.

How do you convert a string to an array of integers?

The string. split() method is used to split the string into various sub-strings. Then, those sub-strings are converted to an integer using the Integer. parseInt() method and store that value integer value to the Integer array.

How do you convert text to Array in Python?

You do this by using the built-in list() function and passing the given string as the argument to the function. The text " Learning Python ! " has both leading and trailing whitespace, whitespace between the words "Learning" and "Python", and whitespace between the word "Python" and the exclamation mark.


2 Answers

list(map(int, "1 2 3 4 5".split(" ")))
like image 155
Amadan Avatar answered Sep 23 '22 01:09

Amadan


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

like image 37
John La Rooy Avatar answered Sep 19 '22 01:09

John La Rooy