0

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]

5 Answers 5

3

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]
Sign up to request clarification or add additional context in comments.

1 Comment

This gives output as a list of strings, and not integers
2

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]

Comments

1

Shortest method using 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]
>>> 

Or another one using 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]
>>> 

Heres another similar solution:

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]
>>> 

Comments

0

I hope the below code helps:

result = [int(i) for i in signal.split(',')]
print(result)

Comments

0

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(','))))

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.