Gloom
Gloom

Reputation: 317

How to count the number of columns in a line with python

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?

Upvotes: 0

Views: 900

Answers (3)

AkaSh
AkaSh

Reputation: 526

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

Upvotes: 1

Guillaume
Guillaume

Reputation: 549

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

Upvotes: 6

Kapil Rupavatiya
Kapil Rupavatiya

Reputation: 141

You just need to check length of spited list:

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

Upvotes: 0

Related Questions