Re: tuple to string?

Discussion in 'Python' started by Qiangning Hong, Jul 22, 2005.

  1. On 7/22/05, Francois De Serres <> wrote:
    > what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to
    > the string 'spam'?


    Use ''.join and chr() as others have pointed out. Here are
    just-for-fun versions ;)

    ..>>> t = (0x73, 0x70, 0x61, 0x6D)

    (use string formatter):
    ..>>> '%c%c%c%c' % t
    'spam'

    (use struct model):
    ..>>> import struct
    ..>>> struct.pack('bbbb', *t)
    'spam'

    --
    Qiangning Hong

    I'm usually annoyed by IDEs because, for instance, they don't use VIM
    as an editor. Since I'm hooked to that, all IDEs I've used so far have
    failed to impress me.
    -- Sybren Stuvel @ c.l.python

    Get Firefox! <http://www.spreadfirefox.com/?q=affiliates&amp;id=67907&amp;t=1>
     
    Qiangning Hong, Jul 22, 2005
    #1
    1. Advertising

  2. QH> On 7/22/05, Francois De Serres <> wrote:
    >> what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to
    >> the string 'spam'?


    QH> Use ''.join and chr() as others have pointed out. Here are
    QH> just-for-fun versions ;)

    ..> t = (0x73, 0x70, 0x61, 0x6D)

    QH> (use string formatter):
    ..> '%c%c%c%c' % t

    Or more generally:

    >>> t = (0x73, 0x70, 0x61, 0x6D)
    >>> '%c'*len(t) % t

    'spam'

    but that's VERY perlonic python. Still, it's a technique that can
    come in handy when building, say, SQL queries on the fly.

    --
    Patricia J. Hawkins
    Hawkins Internet Applications
    www.hawkinsia.com
     
    Patricia J. Hawkins, Jul 23, 2005
    #2
    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. Michal Mikolajczyk
    Replies:
    1
    Views:
    838
    Larry Bates
    Apr 20, 2004
  2. Jeff Epler
    Replies:
    0
    Views:
    1,046
    Jeff Epler
    Apr 20, 2004
  3. Bill Scherer
    Replies:
    0
    Views:
    637
    Bill Scherer
    Apr 20, 2004
  4. Gregor Horvath

    Why tuple with one item is no tuple

    Gregor Horvath, Mar 15, 2005, in forum: Python
    Replies:
    37
    Views:
    868
    Antoon Pardon
    Mar 30, 2005
  5. Steve
    Replies:
    1
    Views:
    1,003
    Fredrik Lundh
    Dec 13, 2005
Loading...

Share This Page