14

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

2
  • 2
    What do you want to know ? If every number is in the list ? Or which ones are in it ? Commented Mar 26, 2017 at 18:55
  • 2
    I want to know if any of the numbers are in the string. Commented Mar 26, 2017 at 18:57

4 Answers 4

23

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)
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.