[英]How to check if a string contains specific characters in a list in Python?
[英]how to check if a list contains a specific string or not in python
我想搜索列表是否包含字符串。 以下代碼無法編譯。
list= []
list.append("item1")
list.append("item2")
list.append("item3")
if 'item1' in list
print "yes"
else
print "no"
錯誤:
File "<string>", line 1, in <module>
File "/usr/lib/python2.7/py_compile.py", line 117, in compile
raise py_exc
py_compile.PyCompileError: File "prog.py", line 6
if 'item1' in command
^
SyntaxError: invalid syntax
如果在if語句/ else語句之后需要一個冒號。
另外,我相信python在使用print時必須像print( MESSAGE )。 編輯:使用方括號是python3中的新方法。
嘗試這個:
list= []
list.append("item1")
list.append("item2")
list.append("item3")
if 'item1' in list:
print("yes")
else:
print("no")
Python中if語句的語法是
if *condition*:
statements
else:
statements
在您的代碼中,if和else部分缺少一個冒號(:)。
list= []
list.append("item1")
list.append("item2")
list.append("item3")
print True if "item1" in list else False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.