![](/img/trans.png)
[英]How to check whether a character comes before another character in a string in Python
[英]How to check whether a string is a concatenation of other strings with a character inserted between each string in python
我正在尝试检查用户输入的字符串是否包含在其他字符串列表中,以及这些字符串的任何排列,并用“ *”分隔。
换句话说,这是我到目前为止的代码:
user_string=raw_input("Please supply a string")
viable_entries=['this', 'that', 'something else']
if user_string in viable_entries:
print "here I'd move on with my script"
如果user_string =“ this * that”或“ this * that”等,我也想打印“我将继续执行脚本的内容”。
有一种简单的,pythonic的方法来做到这一点吗?
您可以拆分输入并使用set.issubset
:
if set(user_string.split('*')).issubset(viable_entries):
...
请注意,即使重复输入( "this*this"
),这也将返回True
。 如果要防止用户提供重复的条目,可以使用len(set)
:
entries = user_string.split('*')
if set(entries).issubset(viable_entries) and len(set(entries)) == len(entries):
...
ecatmur的解决方案更好,但是“强力”方法是生成一组viable_entries并基于此进行检查。 改编自itertools页面:
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (2,1) (3,1) (3,2) (1,2,3)..."
s = list(iterable)
return chain.from_iterable(permutations(s, r) for r in range(len(s)+1))
之后, "*".join(X) for X in powerset(viable_entries)
您提供匹配的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.