如何使用 Python 2 检查字符串中是否包含多个特定字符?
例如,给定以下字符串:
罪犯偷走了 1,000,000 美元的珠宝。
如何检测它是否有美元符号 (“$”)、逗号 (“,”) 和数字?
原文由 The Woo 发布,翻译遵循 CC BY-SA 4.0 许可协议
如何使用 Python 2 检查字符串中是否包含多个特定字符?
例如,给定以下字符串:
罪犯偷走了 1,000,000 美元的珠宝。
如何检测它是否有美元符号 (“$”)、逗号 (“,”) 和数字?
原文由 The Woo 发布,翻译遵循 CC BY-SA 4.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 许可协议
2 回答5.2k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
2 回答834 阅读✓ 已解决
假设您的字符串是
s
:其他角色依此类推。
… 要么
… 要么
[编辑:添加了
'$' in s
答案]