Easy way to convert a unicode list to a list containing python strings?

前端 未结 9 2050
臣服心动
臣服心动 2020-12-23 16:42

Template of the list is:

EmployeeList =  [u\'\', u\'\', u\'\', u\'\']

I would like to con

相关标签:
9条回答
  • 2020-12-23 17:35

    Encode each value in the list to a string:

    [x.encode('UTF8') for x in EmployeeList]
    

    You need to pick a valid encoding; don't use str() as that'll use the system default (for Python 2 that's ASCII) which will not encode all possible codepoints in a Unicode value.

    UTF-8 is capable of encoding all of the Unicode standard, but any codepoint outside the ASCII range will lead to multiple bytes per character.

    However, if all you want to do is test for a specific string, test for a unicode string and Python won't have to auto-encode all values when testing for that:

    u'1001' in EmployeeList.values()
    
    0 讨论(0)
  • 2020-12-23 17:35

    Just simply use this code

    EmployeeList = eval(EmployeeList)
    EmployeeList = [str(x) for x in EmployeeList]
    
    0 讨论(0)
  • 2020-12-23 17:39

    We can use map function

    print map(str, EmployeeList)
    
    0 讨论(0)
提交回复
热议问题