9

I want to join a unicode python list, for example:

a = [u'00', u'0c', u'29', u'58', u'86', u'16']

I want a string that looks like this:

'00:0c:29:58:86:16'

How would I join this?

Brad Koch
  • 19,267
  • 19
  • 110
  • 137
wagner-felix
  • 855
  • 3
  • 9
  • 19

2 Answers2

18
>>> a = [u'00', u'0c', u'29', u'58', u'86', u'16']
>>> u":".join(a)
u'00:0c:29:58:86:16'
>>> str(u":".join(a))
'00:0c:29:58:86:16'
MattH
  • 37,273
  • 11
  • 82
  • 84
  • 1
    Or the other way: `b':'.join(str(item) for item in a)` – agf Oct 18 '11 at 09:07
  • I tried this and I keep getting a `UnicodeDecodeError` about unicode characters with an accent. Does anyone knows why? – Rafael S. Calsaverini Oct 17 '12 at 19:06
  • @RafaelS.Calsaverini: If your error is on the `str` part of this solution it is because the character cannot be represented in ascii. If you need your unicode string in ascii you will have to make an approximation, try a solution like this one: http://stackoverflow.com/a/8087466/267781 – MattH Oct 17 '12 at 20:35
-2

How about this:

if __name__ == "__main__":
        a = [u'00', u'0c', u'29', u'58', u'86', u'16']

        s = u''
        j = True

        for i in a:
                if j == True:
                        s += i
                        j = False
                else:
                        s += u':' + i

        print s
fredley
  • 32,953
  • 42
  • 145
  • 236
lxgeek
  • 1,732
  • 2
  • 22
  • 33