Home > Back-end >  Conversion of strings in list to int - not converting
Conversion of strings in list to int - not converting

Time:11-04

I am trying to convert a list which previously has some integer values, strings and floats all to integers, however am running into some issues during the conversion. Here is what I have done:

class NumbersIterable:
    def __init__(self, numbers):
        self.numbers = numbers
        print(self.numbers)
    
    def runConversion(self):
        return NumbersIterator.convertNumbers(self.numbers)

class NumbersIterator:
    def convertNumbers(numbers):
        print('in numbers')
        for i in numbers:
            int(i)
        print(numbers)
        return numbers

niterable = NumbersIterable(["1", 2.0, "4",5,6.1,"7",8,9.2])
niterable = niterable.runConversion()

sum = 0
for i in niterable:
    print(i)
    sum  = i
print("sum =", sum)

I have some print statements along the way to verify the process, however after it runs through the for loop in NumbersIterator, the print statement shows the values in the list are not converted to integers and as such a error is thrown when running the for loop further down.

Is there anything I might be missing/spelling incorrectly here? Thanks

CodePudding user response:

You can use a simple list comprehension to convert all numbers:

def convertNumbers(numbers):
    return [int(i) for i in numbers]

CodePudding user response:

In your code, int(i) converts i into an integer, and then throws it away. You need to store the converted value in a list. One way of doing so, among many others, is initializing an empty list and then appending int(i):

class NumbersIterator:
    def convertNumbers(numbers):
        print('in numbers')
        output = []
        for i in numbers:
            output.append(int(i))
        print(numbers)
        return output
  • Related