0

I am writing a python code and I am trying to figure out which function would be the best to carry out the following task:

I want to say "if the number of words in a line isn't equal to 1, do stuff"

#Some code
words = line.split("\t")
if sum(words) != 1
#Do something

#Some code
words = line.split("\t")
if int(words) != 1
#Do something

#Some code
words = line.split("\t")
if len(words) != 1
#Do something

All of these commands return the following error:

File "test.py", line 10
if len(words) != 1
                 ^
SyntaxError: invalid syntax

Can anyone help?

1
  • 1
    ...you're missing a colon. Commented Oct 13, 2015 at 10:35

3 Answers 3

6

You are getting this error because you are missing colons after every "if" statement. Also, to get the number of elements in words, you should use len() instead of sum().

This

if sum(words) != 1
#Do something

Should be this:

if len(words) != 1:
#Do something
Sign up to request clarification or add additional context in comments.

Comments

1
if(len(line.split(" "))!=1) :
    do something

4 Comments

split already gives a list, this is not correct. docs.python.org/2/library/stdtypes.html#str.split
line.split() will return a list, no need to list() it again.
@Ruben Though split returns a list the previous answer gives you right answer
Agreed, but a correct output isn't always a right answer.
0

You just need to check length of spited list:

if len(words) != 1:
    #Do your stuff here

1 Comment

Thanks for your help, guys :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.