检查字符串是否只包含给定的字符 [英] Check if a string contains only given characters
本文介绍了检查字符串是否只包含给定的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有比遍历它更优雅的方法来检查字符串 (str = 'abcccbbaabcbca') 是否只包含 'a'、'b' 或 'c':
I'm wondering if there is more elegant way to check if the string (str = 'abcccbbaabcbca') contains only 'a','b' or 'c' than iterating over it :
for i in str:
if i in ['a','b','c']:
pass
else :
print('wrong character')
推荐答案
你可以使用 any
带有生成器表达式:
You could use any
with a generator expression:
if any(c not in 'abc' for c in _str): # Don't use str as a name.
print('Wrong character')
这篇关于检查字符串是否只包含给定的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文