3

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

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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/…
1

Unpack the tuples, convert to a string and repack.

answered Feb 2, 2017 at 21:27

Comments

1
tuple(map(str, unicode_tuple_list))
answered Mar 10, 2017 at 10:04

1 Comment

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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.