2

I have some tuples from an sql query that are a list of album names. However, they output in unicode giving it u' before each name, which I would like to remove. It prints out like this:

((u'test',), (u'album test',), (u'test!',), (u'',), (u'album1',), (u'album2',), (u'album3',), (u'testalbum',))

but i'm looking for just the names such as: test, test, album1, album2 etc.

I've tried using a for loop to encode each album name indivudally, but then i get:

AttributeError: 'tuple' object has no attribute 'encode'

Any suggestions? thank you for your feedback!

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
helloworld
  • 399
  • 3
  • 9
  • 21
  • The tuples look weird. Why are their second elements missing? A string like `u'something'` is known as a unicode string. The rules for converting a Unicode string into the ASCII encoding, for example, are simple; for each code point: If the code point is < 128, each byte is the same as the value of the code point. If the code point is 128 or greater, the Unicode string can't be represented in this encoding. https://docs.python.org/3/howto/unicode.html – kgf3JfUtW Oct 28 '17 at 06:43
  • 1
    Also, please provide your code. – kgf3JfUtW Oct 28 '17 at 06:46
  • Also don't post images. Hard to cut-n-paste to formulate an answer. – Mark Tolonen Oct 28 '17 at 18:20
  • 1
    @sam `(u'test')` isn't a tuple; it is a string with parentheses around it. `(u'test',)` is a one-element tuple. – Mark Tolonen Oct 28 '17 at 18:22
  • @MarkTolonen Oh thank you so much for pointing that out. Didn't know that! – kgf3JfUtW Oct 29 '17 at 00:49
  • 1
    @sam Also FYI, parentheses for the tuple aren't required either, but they are shown for display. `t = u'test',` is also a one-element tuple. – Mark Tolonen Oct 29 '17 at 02:12

2 Answers2

1

Looks like you are calling encode() on the tuple. You really should be calling encode() on the (Unicode) string, which is the first element of the tuple.


For example,

>>> t = (u'hello', u'world')
>>> t.encode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'encode'
>>> t[0].encode()
'hello'
kgf3JfUtW
  • 13,702
  • 10
  • 57
  • 80
0

If you don't want the default output of tuples and Unicode strings, print the strings:

>>> t=(u'test',),(u'album test',),(u'test!',),(u'',),(u'album1',),(u'album2',),(u'album3',),(u'testalbum',)
>>> for item in t:
...   print item[0]
...
test
album test
test!

album1
album2
album3
testalbum
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251