使用.join()插入unicode字符

Mat*_*att 5 python unicode join python-2.7

我在数据表中有我需要加入的列.一列由值组成,另一列由相应的错误值组成,例如:

50.21  0.03
43.23  0.06
23.65  1.20
12.22  0.06
11.25  2.21
Run Code Online (Sandbox Code Playgroud)

我想要做的是,对于每一行连接列和+/-,但干净的unicode字符(U + 00B1).我之前从未尝试过在python中使用unicode字符,所以我很难过.

如果我.join()看起来像

"<unicode here>".join(item)
Run Code Online (Sandbox Code Playgroud)

我怎么让python知道我想使用unicode字符.

Mar*_*ers 6

如果要使用unicode加入,请使用unicode字符串:

u'\u00b1'.join(item)
Run Code Online (Sandbox Code Playgroud)

这确实假设item是一系列字符串 ; 字节字符串或unicode字符串.使用ASCII编解码器,字节字符串将被强制为unicode.

最好将您的值显式转换为unicode字符串,这样您就可以控制使用的编码.

演示str值:

>>> 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
Run Code Online (Sandbox Code Playgroud)

  • @Matt:相关:[让Emacs在Python交互模式下使用UTF-8](http://stackoverflow.com/q/888406) (2认同)