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

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

例如,给定以下字符串:

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

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

最佳答案

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

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

https://stackoverflow.com/questions/5188792/

相关文章:

linux - 重定向 curl 后获取最终 URL

python - 解析 .py 文件,读取 AST,修改它,然后写回修改后的源代码

linux - 如何反汇编原始 16 位 x86 机器代码?

mysql - 复制整个 MySQL 数据库

python - 字符串和字节字符串有什么区别?

regexp)": what d">python - 命名正则表达式组 "(?Pregexp)": what d

python - 值错误 : setting an array element with a seq

linux - 亚马逊 Linux : "apt-get: command not found"

bash - 试图在 Bash 的变量中嵌入换行符

python - 为什么 Python 的原始字符串文字不能以单个反斜杠结尾?