jakethefake
jakethefake

Reputation: 326

Check if any of a list of strings is in another string

In python, I'm trying to create a program which checks if 'numbers' are in a string, but I seem to get an error. Here's my code:

numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]

test = input()

print(test)
if numbers in test:
    print("numbers")

Here's my error:

TypeError: 'in <string>' requires string as left operand, not list

I tried changing numbers into numbers = "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" which is basically removed the [] but this didn't work either. Hope I can get an answer; thanks :)

Upvotes: 14

Views: 16146

Answers (4)

niraj
niraj

Reputation: 18208

Other possible way may be to iterate through each character and check if it is numeric using isnumeric() method:

input_string = input()

# to get list of numbers
num_list = [ch for ch in input_string if ch.isnumeric()]
print (num_list)

# can use to compare with length to see if it contains any number
print(len(num_list)>0)

If input_string = 'abc123' then, num_list will store all the numbers in input_string i.e. ['1', '2', '3'] and len(num_list)>0 results in True.

Upvotes: 1

AstroSloth
AstroSloth

Reputation: 33

As NPE said, you have to check every single digit. The way i did this is with a simple for loop.

for i in numbers:
    if i in test:
        print ("test")

Hope this helped :)

Upvotes: 0

NPE
NPE

Reputation: 500277

In a nutshell, you need to check each digit individually.

There are many ways to do this:

For example, you could achieve this using a loop (left as an exercise), or by using sets

if set(test) & set(numbers):
  ...

or by making use of str.isdigit:

if any(map(str.isdigit, test)):
  ...

(Note that both examples assume that you're testing for digits, and don't readily generalize to arbitrary substrings.)

Upvotes: 3

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Use built-in any() function:

numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
s = input()

test = any(n in s for n in numbers)
print(test)

Upvotes: 23

Related Questions