0

If I wanted to make sure a certain character/word is in a string how could I do that? Like in this example (which is a very ugly) I want to know if a string contains a number.

n = "I have 3 cats"

if "1" in n or "2" in n or "3" in n or "4" in n \
   or "5" in n or "6" in n or "7" in n or "8" in n \
   or "9" in n or "0" in n:
    print "This string contains a number"
else:
    print "This string does not contain a number"

This is a very slow and messy looking way to know if the string contains a number. So how could I make it do something along these lines:

n = "I have 3 cats"
myList = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]

if '''Any of the strings in myList''' in n:
    print "This string contains a number"
else:
    print "This string does not contain a number"

I have looked around Stack Overflow for this answer and couldn't find it so if this is a duplicate I am very sorry! I can't imagine I am the first to have this question?

BTW THIS IS NOT A DUPLICATE OF "How to find if string contains a number" because I am just using the digit example in this case. I just want to know if there is a way to find if a string contains any strings within a list. For example say I wanted to find if a string contains any of these characters "/ \ - _ (), etc." This is not a duplicate

user3678184
  • 85
  • 1
  • 9
  • Hmmm my question is similar to this but only in this example. I want to find a way to know if there is a certain character in a string that is in a list. I just used the digits example in this question. @AntP – user3678184 May 31 '14 at 22:08

2 Answers2

3

You can use any:

if any(d in n for d in myList):

Or, using the str instance method isdigit to make your purpose clearer:

if any(c.isdigit() for c in n):
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
2

Easiest and most efficient is to put the things you want to look for into a set, and check for intersection with that set. (The argument to set.intersection doesn't have to be a set itself.)

digits = set("0123456789")
if digits.intersection(myList):
    print "Yep"
Sneftel
  • 40,271
  • 12
  • 71
  • 104