-3

I have a string that consists of numbers with a space.

myString = "3 45 12"

I want to make a list of integer values derived from that string, ex:

myList = [3, 45, 12]
3
  • Please refer stackoverflow.com/questions/642154/… Commented Mar 27, 2018 at 6:52
  • @user2249207: that's only half the solution. Commented Mar 27, 2018 at 6:54
  • 2
    A simple 1 line solution: myList = [int(i) for i in myString.split()] Commented Mar 27, 2018 at 6:59

1 Answer 1

3

Try this:

myString = "3 45 12"
numericdata = myString.split(' ')
numbers = []

for i in numericdata:
    numbers.append(int(i))

print(numbers)
Sign up to request clarification or add additional context in comments.

8 Comments

it works, thank you!
@Sohib Welcome! and if it works than please accept the answer! Thankyou! :)
what if I had negative numbers in my string as well? I am receiving this error: numbers.append(int(i)) ValueError: invalid literal for int() with base 10: 'f' I think it is related to negative integers in the string.
i think it doesn't matter if you have negative numbers to it will works fine unless you have a space in negative sign. are you using negative numbers like this : - 2 or like this: -2
I am using as -2. Actually this a part of a code I am writing, your code is working separately, but when I insert inside another code, I have an error as I commented above.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.