如何检查字符串中的特定字符?

新手上路,请多包涵

如何使用 Python 2 检查字符串中是否包含多个特定字符?

例如,给定以下字符串:

罪犯偷走了 1,000,000 美元的珠宝。

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

原文由 The Woo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 178
2 个回答

假设您的字符串是 s

 '$' in s        # found
'$' not in s    # not found

# original answer given, but less Pythonic than the above...
s.find('$')==-1 # not found
s.find('$')!=-1 # found

其他角色依此类推。

… 要么

pattern = re.compile(r'\d\$,')
if pattern.findall(s):
    print('Found')
else
    print('Not found')

… 要么

chars = set('0123456789$,')
if any((c in chars) for c in s):
    print('Found')
else:
    print('Not Found')

[编辑:添加了 '$' in s 答案]

原文由 dappawit 发布,翻译遵循 CC BY-SA 3.0 许可协议

用户 Jochen Ritzel 在评论用户 dappawit 对这个问题的回答时这样说。它应该工作:

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

“1”、“2”等应替换为您要查找的字符。

有关字符串的一些信息,请参阅 Python 2.7 文档中的此页面,包括关于使用 in 运算符进行子字符串测试。

更新: 这与我上面的建议相同,重复更少:

 # 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

原文由 Abbafei 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题