-2

I want to have a string, for example I want to type in 'I have 2 dogs' and I want the shell to return True (A function will do) if a number is shown in the string. I found it so hard to code without using any loops and without any 're' or 'string' library.

Any help please?

Example:

input: "I own 23 dogs"
output: True

input: "I own one dog"
output: False
martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

1
>>> a = "I own 23 dogs"
>>> print(bool([i for i in a if i.isdigit()]))
True

>>> b = "I own some dogs"
>>> print(bool([i for i in b if i.isdigit()]))
False

However the better solution is to use any and use generators instead of lists for better performance (just like @Alderven solution):

>>> a = "I own 23 dogs"
>>> any(i.isdigit() for i in a)
True
Mojtaba Kamyabi
  • 3,440
  • 3
  • 29
  • 50
1

List comprehension helps you:

def is_digit(string):
    return any(c.isdigit() for c in string)

print(is_digit("I own 23 dogs"))
print(is_digit("I own one dog"))

Output:

True
False
Alderven
  • 7,569
  • 5
  • 26
  • 38