当我运行下面的代码时,我得到:
Thank you for joining, ['cars', 'gas', 'jewelry']but['bus', 'join'] are not keywords.
如何有效地将列表转换为仅打印的字符串?我怀疑我可能需要一个正则表达式...这次:)
import re
pattern = re.compile('[a-z]+', re.IGNORECASE)
text = "join cars jewelry gas bus"
keywordset = set(('cars', 'jewelry', 'gas', 'food', 'van', 'party', 'shoes'))
words = pattern.findall(text.lower())
notkeywords = list(set(words) - keywordset)
keywords = list(keywordset & set(words))
if notkeywords == ['join']:
print "Thank you for joining keywords " + str(keywords) + "!"
else:
print "Thank you for joining, " + str(keywords) + "but" + str(notkeywords) + " are not keywords."
答案 0 :(得分:1)
要将列表转换为字符串,请使用str.join这样的
print "Thank you for joining keywords " + ",".join(keywords) + "!"
此if notkeywords == ['join']:
不是比较列表元素的方法。
>>> mylist = [1,2]
>>> mylist == 1
False
你应in
运营商检查是否相等。
>>> mylist = [1,2]
>>> 1 in mylist
True
答案 1 :(得分:0)
只需使用someString.join(list)
:
if notkeywords == ['join']:
print "Thank you for joining keywords " + ", ".join(keywords) + "!"
else:
print "Thank you for joining, " + ", ".join(keywords) + "but" + ", ".join(notkeywords) + " are not keywords."
答案 2 :(得分:0)
如果我正确理解了您的问题,您将需要使用.join()字符串方法在打印之前组合列表。
例如:
','。join(my_list)
会给你逗号分隔的输出。 ','可以是你喜欢的任何类型的分隔符。