1

I try to separate digits from a string with some simple code:

d=['72olle' ,'103doo', '100ya']

def only_digit (data):
    return ''.join(filter(lambda x: x.isdigit(),(i for i in data)))

for i in d:
    print(only_digit(i))

print(only_digit(i for i in d))

and can't get why does first print works but second doesn't

SpI
  • 23
  • 4
  • It works to me! – R. García Mar 10 '19 at 14:59
  • 1
    Hey @Spl! What exactly did you expect to happen when running the second print statement? - What is your output supposed to look like? – Maurice Mar 10 '19 at 15:02
  • I thought that two statements are equal, but second didn't work. I want to clarify to myself why it won't work. And i steel don't understand (( – SpI Mar 10 '19 at 15:31

2 Answers2

1

This should give you some info on what is being passed to the only_digit function and what's being returned.

d=['72olle' ,'103doo', '100ya']

def only_digit (data):
    print(type(data)," => ",data)
    theReturn = ''.join(filter(lambda x: x.isdigit(),(i for i in data)))
    print(type(theReturn)," => ",theReturn)
    return theReturn

for i in d:
    print(only_digit(i))

print(only_digit(i for i in d))

Output:

>>> for i in d:
...     print(only_digit(i))
...
<type 'str'>  => ' 72olle '
<type 'str'>  => ' 72 '
72
<type 'str'>  => ' 103doo '
<type 'str'>  => ' 103 '
103
<type 'str'>  => ' 100ya '
<type 'str'>  => ' 100 '
100
>>> print(only_digit(i for i in d))
<type 'generator'>  => ' <generator object <genexpr> at 0x0000000001F764C8> '
<type 'str'>  => '  '
Daviid
  • 630
  • 4
  • 17
  • I see... all that functional orientated staff looks great but cause so many troubles ( Maybe you can show how it should look in a proper functional-style way, thanks for the help ) – SpI Mar 10 '19 at 15:37
  • @Spl Not sure what you mean by functional-style. – Daviid Mar 10 '19 at 17:49
  • @Spl Not sure what you mean by functional-style. Since it looks like you want to do the same as in the first case but in a single line that would be: `print '\n'.join([only_digit(i) for i in d])` `[only_digit(i) for i in d]` is a list comprehension, a for loop in a single line. That returns a list, in this case the results of `only_digit(i)`. Then we join the elements of the list with a new-line, which gives us a string and print it. – Daviid Mar 10 '19 at 17:56
0

You could do the same operation with this different approach, also I think is more easy to understand. Using findall() function from re module:

import re

d=['72olle' ,'103doo', '100ya']
print([re.findall(r'\d+', i)[0] for i in d])

Output:

['72', '103', '100']

References: Python: Extract number from a string

R. García
  • 815
  • 9
  • 20
  • If you know RegEx you can understand this, but claiming that using Regex makes anything easier to understand is bold ;-) – Maurice Mar 10 '19 at 15:27
  • Yes, you are right some RegEx statements are complicated but in this case... it's enoughly easy to use it ;) – R. García Mar 10 '19 at 15:30