Python Forum

Full Version: List conversion and multiplication
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I am trying to work my way through some practice exercises where the objective is to convert a string containing numbers, so that I am able to multiply those numbers to each other. A key requirement is that whenever there is a zero that number gets skipped.

For example, if I have the string “123405”, the multiplication would look like this: 1*2*3*4*5 yielding 120.

My problem isn’t so much the if statement, as much as how to convert the string to an integer or float and then parse this to a series of numbers that I can multiply.

Could you please provide pointers or suggestions on how to approach this problem?

Thank you!
list('123405') would give you a list of the individual characters in the list. You could then use a for loop, convert each character to an integer with the int() built-in, and multiply it (if it's not zero).
Thank you that answered my question perfectly.

Wishing you all the best for the holidays and new year!
You don't need to create the list, since strings are also sequences. That means you can iterate over them directly:

>>> for c in "foo":
...     print(c)
... 
f
o
o
>>> 
Thank you for responding. That makes sense. Also my question has been answered so I will be closing this thread. Btw, happy new year!
Starting from Python 3.8 there is prod function in built-in math module.

>>> import math
>>> s = '123405'
>>> nums = (int(num) for num in s if num != '0')  
>>> math.prod(nums)
120
In code above nums is generator expression and generators will exhaust after first usage.