0

Split space separated Numerical String into a List containing Numbers.

I want this:-

A = '5 2 12 4 29'

to be this in single line of code

B = [5,2,12,4,29]

5 Answers 5

2

You can also use the lambda function as following:

A = '5 2 12 4 29'
B = list(map(lambda x: int(x), a.split()))
print(B)

where split() returns a list of strings and then map function iterates over each string where lambda function converts each string to Integer.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah thanks Mr. Subhash but a simple int will do that without using Anonymous function
Yes sir. Just providing you the options and possibilities.
0

Try this

.split() method returns a list of splitted strings. So you can iterate over it and convert it to a integer

A = '5 2 12 4 29'
B = [int(l) for l in A.split()]
['5', '2', '12', '4', '29']

.split() method will return something like this. But you want them in integers. So you can follow the above method

Comments

0

You can use in python3 this style:

A = '5 2 12 4 29'
B = A.split(" ")

In this case, the split method, with the quotes is used to separate with spaces, as the A has number with spaces, then the quotes to separate would be split(" ")

print(B)
# ['5', '2', '12', '4', '29']

2 Comments

Simply .split() will do
Thanks for your efforts Bro But I need them in integers.
0

Here is a one-liner using a list comprehension:

A  = '5 2 12 4 29'
B = [int(x) for x in A.split()]
print(B)  # [5, 2, 12, 4, 29]

Comments

0

You can use split( ) to convert the string to a list of individual characters. ['5', '2', '12', '4', '29']

Since you want integers and not characters, you can use map() to convert those individual characters to integers.

A = '5 2 12 4 29'
B = list(map(int,A.split()))
print(B)
[5, 2, 12, 4, 29]

Comments

Your Answer

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