1

trying to remove \u0141 from this list which i am trying to insert into my database

results=[['The Squid Legion', '0', u'Banda \u0141ysego', '1', ["\nRazer's Clash of the Gods EU #12 - \nChallonge\n"]], ['Romanian eSports', '1', 'Love', '0', ["\nRazer's Clash of the Gods EU #12 - \nChallonge\n"]]]

results =[[x.encode('ascii', 'ignore')  for x in l] for l in results]

I am getting this error:

AttributeError: 'list' object has no attribute 'encode'
5
  • 4
    Your list is at least 3 levels deep but you're only iterating 2 levels. Commented Mar 6, 2014 at 17:03
  • 1
    And some of your strings are only 2 levels deep. Commented Mar 6, 2014 at 17:03
  • The last x for each l is a list. Commented Mar 6, 2014 at 17:04
  • can you please explain ? I am still new to this Commented Mar 6, 2014 at 17:09
  • @user3386406: your list structure is [[smth, smth, [smth]], ...] but your algorithm expects [[smth, smth, smth], ...]; see my answer for a working algorithm. Commented Mar 6, 2014 at 17:16

1 Answer 1

3

The first list in your "big list" itself contains a list ["\nRazer's Clash of the Gods EU #12 - \nChallonge\n"], which obviously doesn't have an encode() method on it.

So what happens in your algorithm is this:

[[somestring.encode, somestring.encode, somestring.encode, [somestring].encode, ...]

You could use a simple recursive algorithm though:

def recursive_ascii_encode(lst):
    ret = []
    for x in lst:
        if isinstance(x, basestring):  # covers both str and unicode
            ret.append(x.encode('ascii', 'ignore'))
        else:
            ret.append(recursive_ascii_encode(x))
    return ret

print recursive_ascii_encode(results)

outputs:

[['The Squid Legion', '0', 'Banda ysego', '1', ["\nRazer's Clash of the Gods EU #12 - \nChallonge\n"]], ['Romanian eSports', '1', 'Love', '0', ["\nRazer's Clash of the Gods EU #12 - \nChallonge\n"]]]

Of course that's actually a special case of a more general recursive map, which, refactored, looks like this:

def recursive_map(lst, fn):
    return [recursive_map(x, fn) if isinstance(x, list) else fn(x) for x in lst]

print recursive_map(results, lambda x: x.encode('ascii', 'ignore'))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.