Check if there is any list of lines in another line

In python, I am trying to create a program that checks if lines are in a line, but I seem to get an error. Here is my code:

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

test = input()

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

Here is my mistake:

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

I tried changing the numbers to numbers = "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"which I basically deleted [], but that didn't work either. I hope I can get an answer; thank:)

+4
source share
4 answers

Use the built-in function any () :

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

test = any(n in s for n in numbers)
print(test)
+6
source

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

There are many ways to do this:

, , ( ),

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

str.isdigit:

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

( , , .)

+2

Another possible way could be to iterate over each character and check if it is numeric using the method isnumeric():

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_listsave all numbers in input_stringie ['1', '2', '3']and len(num_list)>0result in True.

+1
source

As NPE said, you have to check every digit. The way I did it is a simple loop.

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

Hope this helps :)

0
source

Source: https://habr.com/ru/post/1673244/


All Articles