我如何检查一个字符串是否有几个特定的字符在它使用Python 2?

例如,给定以下字符串:

罪犯们偷了价值一百万美元的珠宝。

我如何检测它是否有美元符号(“$”),逗号(“,”)和数字?


当前回答

这将测试字符串是否由某些组合或数字、美元符号和逗号组成。这就是你想要的吗?

import re

s1 = 'Testing string'
s2 = '1234,12345$'

regex = re.compile('[0-9,$]+$')

if ( regex.match(s1) ):
   print "s1 matched"
else:
   print "s1 didn't match"

if ( regex.match(s2) ):
   print "s2 matched"
else:
   print "s2 didn't match"

其他回答

这将测试字符串是否由某些组合或数字、美元符号和逗号组成。这就是你想要的吗?

import re

s1 = 'Testing string'
s2 = '1234,12345$'

regex = re.compile('[0-9,$]+$')

if ( regex.match(s1) ):
   print "s1 matched"
else:
   print "s1 didn't match"

if ( regex.match(s2) ):
   print "s2 matched"
else:
   print "s2 didn't match"
s=input("Enter any character:")   
if s.isalnum():   
   print("Alpha Numeric Character")   
   if s.isalpha():   
       print("Alphabet character")   
       if s.islower():   
         print("Lower case alphabet character")   
       else:   
         print("Upper case alphabet character")   
   else:   
     print("it is a digit")   
elif s.isspace():   
    print("It is space character")   

其他: print(“非空格特殊字符”)

另一种可能是python式的方法是:

aString = """The criminals stole $1,000,000 in jewels."""
#
if any(list(map(lambda char: char in aString, '0123456789,$')))
   print(True) # Do something.

检查字符串中是否有字符:

parse_string = lambda chars, string: [char in string for char in chars]

例子:

parse_string('$,x', 'The criminals stole $1,000,000 in ....') 

or

parse_string(['$', ',', 'x'], '..minals stole $1,000,000 i..')

输出:[True, True, False]

用户Jochen Ritzel在回复用户dappawit的问题时这样说。 它应该工作:

('1' in var) and ('2' in var) and ('3' in var) ...

'1', '2'等应替换为您正在寻找的字符。

有关字符串的一些信息,包括关于在子字符串测试中使用in操作符的信息,请参阅Python 2.7文档中的此页。

更新:这和我上面的建议是一样的,而且重复次数更少:

# When looking for single characters, this checks for any of the characters...
# ...since strings are collections of characters
any(i in '<string>' for i in '123')
# any(i in 'a' for i in '123') -> False
# any(i in 'b3' for i in '123') -> True

# And when looking for subsrings
any(i in '<string>' for i in ('11','22','33'))
# any(i in 'hello' for i in ('18','36','613')) -> False
# any(i in '613 mitzvahs' for i in ('18','36','613')) ->True