简体   繁体   中英

how to check if a list contains a specific string or not in python

I want to search if a list contains a string or not. The following code does not compile.

list= []         
list.append("item1")         
list.append("item2")         
list.append("item3")     

if 'item1' in list
    print "yes"  
else  
    print "no"  

Error:

 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  

You need a colon after your if statement/else statement.

Also, I believe in python when you use print it has to go like print( MESSAGE ). Edit: Using brackets is the new way in python3.

Try this:

list= []         
list.append("item1")         
list.append("item2")         
list.append("item3")     

if 'item1' in list:
    print("yes")
else: 
    print("no") 

Syntax for if statement in Python is

 if *condition*:
        statements
 else:
        statements

In your code you miss a colon(:) in if and else part.

list= []         
list.append("item1")         
list.append("item2")         
list.append("item3")

print True if "item1" in list else False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM