简体   繁体   中英

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 :)

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)

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.)

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 ie ['1', '2', '3'] and len(num_list)>0 results in True .

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM