What is the best way to convert the values in tuples from unicode to string, when the tuples are in a list, can it be done without looping?
unicodedata.normalize('NKFD', x) can only take unicode, not a tuple. The dataset also includes float values.
EXAMPLE
unicode_tuple_list = [(u'text in unicode', u'more unicode'), (u'more text in unicode', u'even more unicode')]
print type(unicode_tuple_list) # list - keep as list
print type(unicode_tuple_list[0]) # tuple - keep as tuple
print type(unicode_tuple_list[0][0]) # unicode
How can all these values be made a str?
asked Feb 2, 2017 at 20:01
cycle_about
3551 gold badge3 silver badges6 bronze badges
3 Answers 3
I'm not sure there is a way to convert this without using a loop/list comprehension.
I would use the map function to accomplish this, see:
unicode_tuple_list = [(u'text in unicode', u'more unicode'), (u'more text in unicode', u'even more unicode')]
string_tuple_list = [tuple(map(str,eachTuple)) for eachTuple in unicode_tuple_list]
print string_tuple_list
answered Feb 2, 2017 at 20:18
Michael Goodwin
7301 gold badge6 silver badges17 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
cycle_about
Thank you Michael, this works great except for a part of the dataset with non-ascii characters. Is there a way to use map to also force encode the tuple values to ascii?
Michael Goodwin
If you don't need to preserve the special characters you could look at this: stackoverflow.com/a/35536228/7108103 if you do need to keep them you can look at this: stackoverflow.com/questions/19527279/…
Unpack the tuples, convert to a string and repack.
answered Feb 2, 2017 at 21:27
The Stupid Engineer
4125 silver badges19 bronze badges
Comments
tuple(map(str, unicode_tuple_list))
answered Mar 10, 2017 at 10:04
greenbergé
3312 silver badges9 bronze badges
1 Comment
Donald Duck is with Ukraine
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
Explore related questions
See similar questions with these tags.
lang-py