如何检查字符串中的特定字符? [英] How to check a string for specific characters?

查看:41
本文介绍了如何检查字符串中的特定字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I check if a string has several specific characters in it using Python 2?

例如,给定以下字符串:

For example, given the following string:

犯罪分子偷走了价值 1,000,000 美元的珠宝.

The criminals stole $1,000,000 in jewels.

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

How do I detect if it has dollar signs ("$"), commas (","), and numbers?

推荐答案

假设你的字符串是 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')

这篇关于如何检查字符串中的特定字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆