Python - trying to multiply items in a list

So basically what I am trying to do here is ask the user to enter a random string input, for example:

asdf34fh2

And I want to bring the numbers from them to the list and get [3,4,2], but I keep getting [34, 2].

import re 

def digit_product():        
    str1 = input("Enter a string with numbers: ")

    if str1.isalpha():
        print('Not a string with numbers')
        str1 = input("Enter a string with numbers: ")
    else:
        print(re.findall(r'\d+', str1))   

digit_product()      

And then I want to take this list of numbers and multiply them, and in the end we get 24.

+4
source share
5 answers

Your regular expression \d+,, is the culprit here. +means that it matches one or more consecutive digits ( \d):

asdf34fh2
    ^-  ^
    \   \_ second match: one or more digits ("2")
     \____ first match: one or more digits ("34")

It looks like you only want to combine one digit, so use \dwithout +.

+7

, .

>>> a = "asdf34fh2"
>>> [i for i in a if i in '0123456789']
['3', '4', '2']

>>> [i for i in a if i.isdigit()]
['3', '4', '2']
0
import re
import functools

def digit_product():

    str=input("Enter a string with numbers: ")
    finded = re.findall(r'\d', str)
    if not finded:
        print('Not a string with numbers')
    else:
        return functools.reduce(lambda x, y: int(x) * int(y), finded)

def digit_product2():
    input_text = input("Enter a string with numbers: ")
    return functools.reduce(lambda x, y: int(x) * int(y), filter(str.isdigit, input_text))

>>> digit_product()
Enter a string with numbers: a2s2ddd44dd
64

>>> digit_product2()
Enter a string with numbers: a2s2ddd44dd
64
0

print(reduce(lambda x, y: x * y, [int(n) for n in text_input if n.isdigit()]))

re. , .

str . .

reduce(lambda … . .

() . , ​​ . .

. ,

print(reduce(lambda x, y: x * y, [int(n) for n in text_input if n.isdigit() and n is not '0']))
0

Regular expressions are slow and often difficult to process. For your purpose, I would recommend built-in functional programming and list expressions:

In [115]: a = "asdf34fh2gh39qw3409sdgfklh"

In [116]: filter(lambda x: x.isdigit(), a)
Out[116]: '342393409'

In [117]: [char for char in filter(lambda x: x.isdigit(), a)]
Out[117]: ['3', '4', '2', '3', '9', '3', '4', '0', '9']
-1
source

Source: https://habr.com/ru/post/1614076/


All Articles