Reputation: 1
I need to create the function that changes a string of comma separated integers with this structure:
signal = ('1,7,6,9,12,21,26,27,25')
If I use this code, two-digit numbers is not correct, because it results in the separation into two numbers
result = [int(i) for i in signal]
Current output: [1, 7, 6, 9, 1, 2, 2, 1, 2, 6, 2, 7, 2, 5]
Expected output: [1,7,6,9,12,21,26,27,25]
Upvotes: 0
Views: 118
Reputation: 1012
I found two ways to your question:
signal = ('1,7,6,9,12,21,26,27,25')
1. first use split to make a list from your string base on ',' character and then use int to change the type of output.
print([int(x) for x in signal.split(',')])
2. another way you can use the map to applying int to the list that created by split method.
print(list(map(int, signal.split(','))))
Upvotes: 0
Reputation: 5048
I hope the below code helps:
result = [int(i) for i in signal.split(',')]
print(result)
Upvotes: 0
Reputation: 7303
eval
list(eval(signal))
Testing:
>>> signal = ('1,7,6,9,12,21,26,27,25')
>>>
>>> list(eval(signal))
[1, 7, 6, 9, 12, 21, 26, 27, 25]
>>>
eval
:eval("[" + signal + "]")
Testing:
>>> signal = ('1,7,6,9,12,21,26,27,25')
>>>
>>> eval("[" + signal + "]")
[1, 7, 6, 9, 12, 21, 26, 27, 25]
>>>
list(map(int, signal.split(",")))
Testing:
>>> signal = ('1,7,6,9,12,21,26,27,25')
>>>
>>> list(map(int, signal.split(",")))
[1, 7, 6, 9, 12, 21, 26, 27, 25]
>>>
Upvotes: 1
Reputation: 22766
In fact, your code raises a ValueError
when trying to convert ','
to an int
, you probably have a tuple
of strings in your actual code (string = ('1','7','6','9','12','21','26','27','25')
, in which case your code should work fine), if not, then another problem is that you're converting each character of the string separately, you should split
the string by a comma first (to avoid the ValueError
and to convert each number rather each digit to int
):
signal = '1,7,6,9,12,21,26,27,25'
result = [int(i) for i in signal.split(',')]
print(result)
Output:
[1, 7, 6, 9, 12, 21, 26, 27, 25]
Upvotes: 2
Reputation: 4189
type(signal)
will tell you data type of signal
is still str
. Take a try of below
x = signal.split(',')
[int(i) for i in x]
Upvotes: 3