Pedro CM
Pedro CM

Reputation: 1

How to change from string to integer

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

Answers (5)

Shahab Rahnama
Shahab Rahnama

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

ngShravil.py
ngShravil.py

Reputation: 5048

I hope the below code helps:

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

Upvotes: 0

Nouman
Nouman

Reputation: 7303

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

Upvotes: 1

Djaouad
Djaouad

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

ComplicatedPhenomenon
ComplicatedPhenomenon

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

Related Questions