-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
  • 112,593
  • 23
  • 157
  • 280

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,167
  • 3
  • 27
  • 48
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
  • 6,120
  • 4
  • 22
  • 35