List conversion and multiplication - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: List conversion and multiplication (/thread-23363.html) |
List conversion and multiplication - johnkyp - Dec-25-2019 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! RE: List conversion and multiplication - ichabod801 - Dec-25-2019 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). RE: List conversion and multiplication - johnkyp - Dec-25-2019 Thank you that answered my question perfectly. Wishing you all the best for the holidays and new year! RE: List conversion and multiplication - ndc85430 - Dec-27-2019 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 >>> RE: List conversion and multiplication - johnkyp - Jan-01-2020 Thank you for responding. That makes sense. Also my question has been answered so I will be closing this thread. Btw, happy new year! RE: List conversion and multiplication - perfringo - Jan-02-2020 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) 120In code above nums is generator expression and generators will exhaust after first usage. |