converting lists to strings to lists

Discussion in 'Python' started by robin, Apr 12, 2006.

  1. robin

    robin Guest

    hi,

    i'm doing some udp stuff and receive strings of the form '0.870000
    0.250000 0.790000;\n'
    what i'd need though is a list of the form [0.870000 0.250000 0.790000]
    i got to the [0:-3] part to obtain a string '0.870000 0.250000
    0.790000' but i can't find a way to convert this into a list. i tried
    eval() but this gives me the following error:

    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    File "<string>", line 1
    .870000 0.250000 0.79000

    and i have the same problem the other way round. e.g. i have a list
    which i need to convert to a string in order to send it via udp.
    btw: i cannot use pickle, since i'm sending stuff to a LISP programme.

    thank you in advance for your help!
    best,

    robin
     
    robin, Apr 12, 2006
    #1
    1. Advertising

  2. robin

    Eric Deveaud Guest

    robin wrote:
    > hi,
    >
    > i'm doing some udp stuff and receive strings of the form '0.870000
    > 0.250000 0.790000;\n'
    > what i'd need though is a list of the form [0.870000 0.250000 0.790000]
    > i got to the [0:-3] part to obtain a string '0.870000 0.250000
    > 0.790000' but i can't find a way to convert this into a list. i tried
    > eval() but this gives me the following error:


    check pydoc string about split

    my_string = '0.870000 0.250000 0.790000;\n'
    my_list = my_string.split()
    print my_list


    > and i have the same problem the other way round. e.g. i have a list
    > which i need to convert to a string in order to send it via udp.



    my_new_string = ' '.join(my_list)
    print my_new_string

    Eric
     
    Eric Deveaud, Apr 12, 2006
    #2
    1. Advertising

  3. robin

    Guest

    Read about string split and join. E.g.:
    l = '0.870000 0.250000 0.790000'
    floatlist = [float(s) for s in l.split()]

    In the other direction:
    floatlist = [0.87, 0.25, 0.79000000000000004]
    outstring = ' '.join(floatlist)

    If you need to control the precision(i.e. suppress the 00004), read
    about
    the string formatting operator "%".

    -- George Young
     
    , Apr 12, 2006
    #3
  4. robin

    robin Guest

    thanks for your answer. split gives me a list of strings, but i found a
    way to do what i want:

    input='0.1, 0.2, 0.3;\n'
    input = list(eval(input[0:-2]))
    print input
    > [0.10000000000000001, 0.20000000000000001, 0.29999999999999999]


    this does fine... but now, how do i convert this list to a string?

    my_new_string = ' '.join(input)

    gives me:

    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    TypeError: sequence item 0: expected string, float found

    thanks,

    robin
     
    robin, Apr 12, 2006
    #4
  5. On Wed, 12 Apr 2006 06:53:23 -0700, robin wrote:

    > hi,
    >
    > i'm doing some udp stuff and receive strings of the form '0.870000
    > 0.250000 0.790000;\n'
    > what i'd need though is a list of the form [0.870000 0.250000 0.790000]
    > i got to the [0:-3] part to obtain a string '0.870000 0.250000
    > 0.790000' but i can't find a way to convert this into a list. i tried
    > eval() but this gives me the following error:
    >
    > Traceback (most recent call last):
    > File "<stdin>", line 1, in ?
    > File "<string>", line 1
    > .870000 0.250000 0.79000



    # untested!
    def str2list(s):
    """Expects a string of the form '0.87 0.25 0.79;\n' and
    returns a list like [0.87, 0.25, 0.79]

    WARNING: this function has only limited error checking.
    """
    s = s.strip() # ignore leading and trailing whitespace
    if s.endswith(';'):
    s = s[:-1]
    L = s.split()
    assert len(L) == 3, "too many or too few items in list."
    return [float(f) for f in L]


    > and i have the same problem the other way round. e.g. i have a list
    > which i need to convert to a string in order to send it via udp.


    That's even easier.

    def list2str(L):
    """Expects a list like [0.87, 0.25, 0.79] and returns a string
    of the form '0.870000 0.250000 0.790000;\n'.
    """
    return "%.6f %.6f %.6f;\n" % tuple(L)



    --
    Steven.
     
    Steven D'Aprano, Apr 12, 2006
    #5
  6. robin

    Peter Hansen Guest

    robin wrote:
    > i'm doing some udp stuff and receive strings of the form '0.870000
    > 0.250000 0.790000;\n'
    > what i'd need though is a list of the form [0.870000 0.250000 0.790000]
    > i got to the [0:-3] part to obtain a string '0.870000 0.250000


    Actually, that's already a bug. You want [0:-2] if you're going to do
    it that way. Unless you meant that your string actually has a backslash
    and an "n" character, which is doubtful...

    You should probably use something more like Steven's solution, although
    I'd personally use s.strip(';') or at least s.rstrip(';') if I had
    semicolons to remove, rather than a combined endswith(';') and slicing
    the last character off.

    > 0.790000' but i can't find a way to convert this into a list. i tried
    > eval() but this gives me the following error:
    >
    > Traceback (most recent call last):
    > File "<stdin>", line 1, in ?
    > File "<string>", line 1
    > .870000 0.250000 0.79000


    (If you'd posted the full error (that's an incomplete traceback),
    someone would probably have pointed out how to interpret what Python
    told you so that you'd already have figured out what was wrong with that...)

    -Peter
     
    Peter Hansen, Apr 12, 2006
    #6
  7. robin

    robin Guest

    yo!

    thank you everone! here's how i finally did it:
    converting the string into a list:

    input = net.receiveUDPData()
    input = list(eval(input[0:-2]))

    converting the list into a string:

    sendout = "%.6f %.6f %.6f;\n" % tuple(winningvector)

    maybe i'll even find a way to generalize the list2string bit, so it
    accepts arbitrary sized lists...
    thanks,

    robin
     
    robin, Apr 12, 2006
    #7
  8. robin wrote:
    > thanks for your answer. split gives me a list of strings,


    Of course, why should it be otherwise ?-)

    More seriously : Python doesn't do much automagical conversions. Once
    you've got your list of strings, you have to convert'em to floats.

    > but i found a
    > way to do what i want:
    >
    > input='0.1, 0.2, 0.3;\n'
    > input = list(eval(input[0:-2]))


    - eval() is potentially harmful. Using it on untrusted inputs is a bad
    idea. In fact, using eval() (or exec) is a bad idea in most cases.

    - removing trailing or leading chars is best done with str.strip()

    Also, your code is not as readable as the canonical solution (split() +
    float)

    > print input
    >
    >>[0.10000000000000001, 0.20000000000000001, 0.29999999999999999]


    input = map(float, input.strip('\n;').split(","))
    [0.10000000000000001, 0.20000000000000001, 0.29999999999999999]

    >
    > this does fine... but now, how do i convert this list to a string?
    >
    > my_new_string = ' '.join(input)
    >
    > gives me:
    >
    > Traceback (most recent call last):
    > File "<stdin>", line 1, in ?
    > TypeError: sequence item 0: expected string, float found


    Same as above - you need to do the conversion:
    ' '.join(map(str, input))


    --
    bruno desthuilliers
    python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
    p in ''.split('@')])"
     
    bruno at modulix, Apr 12, 2006
    #8
  9. robin wrote:
    > yo!
    >
    > thank you everone! here's how i finally did it:
    > converting the string into a list:
    >
    > input = net.receiveUDPData()
    > input = list(eval(input[0:-2]))


    You'll run into trouble with this.

    > converting the list into a string:
    >
    > sendout = "%.6f %.6f %.6f;\n" % tuple(winningvector)
    >
    > maybe i'll even find a way to generalize the list2string bit, so it
    > accepts arbitrary sized lists...


    sendout = "%s;\n" % " ".join(["%.6f" % float(s) for s in winningvector])



    --
    bruno desthuilliers
    python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
    p in ''.split('@')])"
     
    bruno at modulix, Apr 12, 2006
    #9
  10. robin

    Eric Deveaud Guest

    robin wrote:
    > yo!
    >
    > thank you everone! here's how i finally did it:
    > converting the string into a list:
    >
    > input = net.receiveUDPData()
    > input = list(eval(input[0:-2]))


    no pun intented but as you did not know how to use split and join,
    please please DON'T USE eval

    Eric
     
    Eric Deveaud, Apr 12, 2006
    #10
  11. robin

    Dave Hansen Guest

    On 12 Apr 2006 06:53:23 -0700 in comp.lang.python, "robin"
    <> wrote:

    >hi,
    >
    >i'm doing some udp stuff and receive strings of the form '0.870000
    >0.250000 0.790000;\n'
    >what i'd need though is a list of the form [0.870000 0.250000 0.790000]
    >i got to the [0:-3] part to obtain a string '0.870000 0.250000
    >0.790000' but i can't find a way to convert this into a list. i tried
    >eval() but this gives me the following error:
    >
    >Traceback (most recent call last):
    > File "<stdin>", line 1, in ?
    > File "<string>", line 1
    > .870000 0.250000 0.79000
    >
    >and i have the same problem the other way round. e.g. i have a list
    >which i need to convert to a string in order to send it via udp.
    >btw: i cannot use pickle, since i'm sending stuff to a LISP programme.
    >


    Here's a little playing around I did the the interactive interpreter.
    Not guaranteed to be the most efficient or Pythonic, but it seems to
    work...

    >>> instr = '0.870000 0.250000 0.790000;\n'
    >>> instr

    '0.870000 0.250000 0.790000;\n'
    >>> ell = [float(x) for x in instr[:-2].split()]
    >>> print ell

    [0.87, 0.25, 0.79000000000000004]
    >>> outstr = " ".join(["%8.6f"%x for x in ell]) + ";\n"
    >>> outstr

    '0.870000 0.250000 0.790000;\n'
    >>> instr == outstr

    True

    Regards,
    -=Dave

    --
    Change is inevitable, progress is not.
     
    Dave Hansen, Apr 12, 2006
    #11
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. dcMan
    Replies:
    7
    Views:
    1,689
    Chris Uppal
    Nov 23, 2005
  2. Exits Funnel

    converting wide strings to long

    Exits Funnel, Jan 14, 2005, in forum: C++
    Replies:
    2
    Views:
    1,654
    Exits Funnel
    Jan 16, 2005
  3. max
    Replies:
    0
    Views:
    261
  4. =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==

    List of lists of lists of lists...

    =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==, May 8, 2006, in forum: Python
    Replies:
    5
    Views:
    410
    =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==
    May 15, 2006
  5. Ben

    Strings, Strings and Damned Strings

    Ben, Jun 22, 2006, in forum: C Programming
    Replies:
    14
    Views:
    767
    Malcolm
    Jun 24, 2006
Loading...

Share This Page