Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a unicode character using .join()

I have columns in a data table that I need to join. One column consists of values and the other of corresponding error values, for example:

50.21  0.03
43.23  0.06
23.65  1.20
12.22  0.06
11.25  2.21

What I'd like to do is, for each row join the columns along with a +/-, but the clean unicode character (U+00B1). I've never tried to use unicode characters in python before, so I'm sorta stumped.

If my .join() looks like

"<unicode here>".join(item)

how exactly do I let python know I want to use a unicode character.

like image 414
Matt Avatar asked Dec 19 '13 19:12

Matt


1 Answers

If you want to join with unicode, use a unicode string:

u'\u00b1'.join(item)

This does presume that item is a sequence of strings; byte strings or unicode strings. Byte strings will be coerced to unicode for you, with the ASCII codec.

It'd be better to explicitly turn your values into unicode strings, that way you can control what encoding is used.

Demo with str values:

>>> items = [r.split() for r in '''\
... 50.21  0.03
... 43.23  0.06
... 23.65  1.20
... 12.22  0.06
... 11.25  2.21
... '''.splitlines()]
>>> items
[['50.21', '0.03'], ['43.23', '0.06'], ['23.65', '1.20'], ['12.22', '0.06'], ['11.25', '2.21']]
>>> for item in items:
...     print u'\u00b1'.join(item)
... 
50.21±0.03
43.23±0.06
23.65±1.20
12.22±0.06
11.25±2.21
like image 157
Martijn Pieters Avatar answered Sep 30 '22 21:09

Martijn Pieters