Problem with Boolean Expression with a string value from a lIst

I have the following problem:

  # line is a line from a file that contains ["baa","beee","0"]
  line = TcsLine.split(",")
  NumPFCs = eval(line[2])
  if NumPFCs==0:
     print line

I want to print all the lines from the file if the second position of the list has a value == 0.

I print the lines but after that the following happens: Traceback (most recent call last):

['baaa', 'beee', '0', '\n']

BUT after I have the next ERROR", line 141, in ?
    getZeroPFcs()", line 110, in getZeroPFcs
    NumPFCs = eval(line[2])
  File "<string>", line 0

Can you please help me? thanks


Asked by: Daisy444 | Posted: 06-12-2021

Answer 1

Let me explain a little what you do here.

If you write:

NumPFCs = eval(line[2])

the order of evaluation is:

  • take the second character of the string line, i.e. a quote '"'
  • eval this quote as a python expression, which is an error.

If you write it instead as:

NumPFCs = eval(line)[2]

then the order of evaluation is:

  • eval the line, producing a python list
  • take the second element of that list, which is a one-character string: "0"
  • a string cannot be compared with a number; this is an error too.

In your terms, you want to do the following:

NumPFCs = eval(eval(line)[2])

or, slightly better, compare NumPFCs to a string:

if NumPFCs == "0":

but the ways this could go wrong are almost innumerable. You should forget about eval and try to use other methods: string splitting, regular expressions etc. Others have already provided some suggestions, and I'm sure more will follow.

Answered by: Elise734 | Posted: 07-01-2022

Answer 2

Your question is kind of hard to read, but using eval there is definitely not a good idea. Either just do a direct string comparison:

if line[2] == "0":
    print line

or use int

if int(line[2]) == 0:
    print line

Either way, your bad data will fail you.

I'd also recomment reading PEP 8.

Answered by: Darcy525 | Posted: 07-01-2022

Answer 3

There are a few issues I see in your code segment:

  1. you make an assumption that list always has at least 3 elements
  2. eval will raise exception if containing string isn't valid python
  3. you say you want second element, but you access the 3rd element.

This is a safer way to do this

if len(line) >=3 and line[2].rfind("0") != -1:
     print line

Answered by: Maya595 | Posted: 07-01-2022

Answer 4

I'd recommend using a regular expression to capture all of the variants of how 0 can be specified: with double-quotes, without any quotes, with single quotes, with extra whitespace outside the quotes, with whitespace inside the quotes, how you want the square brackets handled, etc.

Answered by: Sienna313 | Posted: 07-01-2022

Answer 5

There are many ways of skinning a cat, as it were :)

Before we begin though, don't use eval on strings that are not yours so if the string has ever left your program; i.e. it has stayed in a file, sent over a network, someone can send in something nasty. And if someone can, you can be sure someone will.

And you might want to look over your data format. Putting strings like ["baa","beee","0", "\n"] in a file does not make much sense to me.

The first and simplest way would be to just strip away the stuff you don't need and to a string comparison. This would work as long as the '0'-string always looks the same and you're not really after the integer value 0, only the character pattern:

TcsLine = '["baa","beee","0"]'

line = TcsLine.strip('[]').split(",")
if line[2] == '"0"':
   print line

The second way would be to similar to the first except that we cast the numeric string to an integer, yielding the integer value you were looking for (but printing 'line' without all the quotation marks):

TcsLine = '["baa","beee","0"]'

line = [e.strip('"') for e in TcsLine.strip('[]').split(",")]
NumPFCs = int(line[2])
if NumPFCs==0:
   print line

Could it be that the string is actually a json array? Then I would probably go get simplejson to parse it properly if I were running Python<2.6 or just import json on Python>=2.6. Then cast the resulting '0'-string to an integer as in the previous example.

TcsLine = '["baa","beee","0"]'

#import json # for >= Python2.6
import simplejson as json # for <Python2.6

line = json.loads(TcsLine)
NumPFCs = int(line[2])
if NumPFCs==0:
   print line

Answered by: Julia778 | Posted: 07-01-2022

Similar questions

python - Is it possible to solve this problem with Regular Expression?

I'm trying to divide long text in small parts, so that every part is at least N characters and ended with some of the stop punctuation marks (? . !). If the part is bigger than N characters we sttoped when the next punctuation mark appear. For example : Lets say N = 10 Do you want lime? Yes. I love when I drink tequila. This sentence should be divided in two ...

regex - Problem with Regular Expression in Python

I have a function in python which returns a tuple of a given key for the Natural-Sort/Human algorithm. See fake _human_key. But I need this to change this to replace German umlauts by their standard alphabetical characters. Long story short, I want to get rid of Ä, Ö, Ü, ß for the sorting. Also, the case should no...

python - How to solve this problem with nltk regular expression?

In the W3C Date Time Format, dates are represented like this: 2009-12-31. Replace the ? in the following Python code with a regular expression, in order to convert the string '2009-12-31' to a list of integers [2009, 12, 31]: [int(n) for n in re.findall(?, '2009-12-31')]

python - what is the problem in my reqular expression

This question already has answers here:

python - Regular expression to match start of filename and filename extension

What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'? The regular expression should match any of the following: It should not match: RunBar.py1 Run42.txt The SQL equivalent of what I am looking for is ... LIKE '' ...

regex - python regular expression to split paragraphs

How would one write a regular expression to use in python to split paragraphs? A paragraph is defined by 2 linebreaks (\n). But one can have any amount of spaces/tabs together with the line breaks, and it still should be considered as a paragraph. I am using python so the solution can use python's regular expression syntax whi...

python - split twice in the same expression?

Imagine I have the following: inFile = "/adda/adas/sdas/hello.txt" # that instruction give me hello.txt Name ="/") [-1] # that one give me the name I want - just hello Name1 = Name.split(".") [0] Is there any chance to simplify that doing the same job in just one expression?

python - Regular expression to extract URL from an HTML link

I’m a newbie in Python. I’m learning regexes, but I need help here. Here comes the HTML source: &lt;a href="" target="_blank"&gt;;/a&gt; I’m trying to code a tool that only prints out Can you help me please?

regex - How can I translate the following filename to a regular expression in Python?

I am battling regular expressions now as I type. I would like to determine a pattern for the following example file: b410cv11_test.ext. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a solution that best matches the file pattern? Thanks in advance.

python - What is the regular expression for the "root" of a website in django?

I'm using django and when users go to I want to point them to the index view. Right now I'm doing this: (r'^$', 'ideas.idea.views.index'), However, it's not working. I'm assuming my regular expression is wrong. Can anyone help me out? I've looked at python regular expressions but they didn't help me.

regex - Python Regular Expression to add links to urls

I'm trying to make a regular expression that will correctly capture URLs, including ones that are wrapped in parenthesis as in ( and spoken about on coding horror at I'm currently using the foll...

python - Regular expression to detect semi-colon terminated C++ for & while loops

In my Python application, I need to write a regular expression that matches a C++ for or while loop that has been terminated with a semi-colon (;). For example, it should match this: for (int i = 0; i &lt; 10; i++); ... but not this: for (int i = 0; i &lt; 10; i++) This looks trivial at first glance, until you realise...

regex - How do i write a regular expression for the following pattern in python?

How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign Case 1: str1=str2 Case 2: str1 = str2 please note there can be a space or none between the either side of the "=" sign Mine is like this, but only works for one of the cases! m=re...

regex - Why is the regular expression returning an error in python?

Am trying the following regular expression in python but it returns an error import re ... #read a line from a file to variable line # loking for the pattern 'WORD' in the line ...'(?&lt;=[WORD])\w+',str(line)) i get the following error: AttributeError: 'NoneType' object has no attribute 'group'

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python