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!
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.
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.
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.
list(map(int, "1 2 3 4 5".split(" ")))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With