one-element tuples

Larry Hudson orgnut at yahoo.com
Tue Apr 12 02:01:50 EDT 2016


On 04/10/2016 08:19 PM, Fillmore wrote:
>
> Thank you for trying to help, Martin. So:
>
> On 04/10/2016 09:08 PM, Martin A. Brown wrote:
>> #1: I would not choose eval() except when there is no other
>>      solution.  If you don't need eval(), it may save you some
>>      headache in the future, as well, to find an alternate way.
>>      So, can we help you choose something other than eval()?
>>      What are you trying to do with that usage?
>
> so, I do not quite control the format of the file I am trying to parse.
>
> it has the format:
>
> "str1","str2",....,"strN" => more stuff
>    :
>
> in some cases there is just one "str" which is what created me problem.
> The first "str1" has special meaning and, at times, it can be alone.
>
> The way I handle this is:
>
>      parts = line.strip().split(" => ")
>      tokens = eval(parts[0])
>

[code deleted...]

> which admittedly is not very elegant. If you have suggestions on how to avoid the use
> of eval() and still achieve the same, I would be delighted to hear them
>
>

Here is a possible alternate approach to get you started thinking in a different direction...

Assuming your input string format is always as you describe, splitting off the trailing 'noise' 
can be done the way you are already doing.  It can be done other ways as well.  (Of course, for 
a 'real' program you will probably need to verify this assumption and take appropriate action if 
necessary.)

parts = line.strip().split(' => ')[0]

Note that this trailing index of 0 will throw away the trailing junk, and leave just the initial 
part of the original line as a string.  This can then be split on the commas to give you a list 
of strings...

tokens = parts.split(',')

This will give you, for example,

['"str1"']   #  Case 1, or
['"str1"', '"str2"', '"str3"', ...]  #  Case 2

There is still a problem here.  The strings CONTAIN beginning and ending quotes INSIDE the 
strings.  We can strip these internal quotes with slicing.  I'm also using a list comprehension 
here...

tokens = [st[1:-1] for st in tokens]

Which gives:  ['str1', 'str2', 'str3', ...]

Finally, there are at least two ways of splitting off the first string:  slicing or pop().

key = tokens[0]; tokens = tokens[1:]
     or
key = tokens.pop(0)    #  This simultaneously removes the first string from the tokens list

Where key is the first string, and tokens is a list of the remaining strings.  This list may be 
empty.  You can now use the key for whatever you need it for, and you can use a for loop for the 
remaining strings.  Note that this also works correctly for an empty list -- where it will do 
nothing.

I hope this gets you started reworking (or re-thinking) your program.




More information about the Python-list mailing list