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

2019-07-29 15:27发布

问题:

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?

回答1:

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:

['¬', '∆']


回答2:

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

for out in output:
    print out