add and print non-ASCII characters to a list-pytho

2019-07-29 14:43发布

With the python I have learn, I have been trying to – when you type in a phrase – translate it into symbols. I tried the maketrans() function, but that didn't worked. Here's my code:

# -*- coding: utf-8 -*-

message = "ab"
output = []
broke = list(message)
limit = len(broke)

for i in range(limit):
    if broke[i] == "a":
        output.append("¬")
    if broke[i] == "b":
        output.append("∆")

If I execute print output I get: ['\xc2\xac'] instead of ¬. Is there any way I could get around this?

2条回答
一夜七次
2楼-- · 2019-07-29 15:17

output is a list of strings. Just print the individual strings:

for out in output:
    print out
查看更多
神经病院院长
3楼-- · 2019-07-29 15:36

In python 3, printing lists doesn't use string escape while in Python 2 it does, so doing the same thing in python 3 will achieve the save result you wanted. To achieve the same result in Python 2, you will have to do:

# -*- coding: utf-8 -*-
import sys

message = "ab"
output = []
broke = list(message)
limit = len(broke)

for i in range(limit):
    if broke[i] == "a":
        output.append("¬")
    if broke[i] == "b":
        output.append("∆")
msg = repr(output).decode('string-escape')
print msg

output will be:

['¬', '∆']
查看更多
登录 后发表回答