如何将 Python 中具有特殊字符的字符串变量转换为正确打印

How to convert a string variable with special characters in Python to print properly

抱歉,如果标题令人困惑,但我已经研究了两个小时,不知道我应该如何提出这个问题,所以任何人都可以随意编辑这个 post。

我有这个字符串变量,它是我使用网络抓取创建的,它使用特殊字符,看起来像“\ud83d\ude00\u0107\u00e7\n hello”,当我打印它时没有引号。问题是我希望它打印实际的特殊字符,但我不确定应该使用哪种编码方法。如果我复制并粘贴确切的字符串并打印它,它工作正常但作为我创建的变量,它不显示特殊字符,只显示文本。

我尝试过使用 json.load、unicode-escape、UTF-8 和其他一些方法将其转换为字符串,但老实说我不确定应该使用哪种方法

page = requests.get('https://www.example.com')
soup = str(BeautifulSoup(page.text, 'html.parser')).splitlines()

for line in soup:
    if 'hello' in line:
        print(line) #produces literal text of \ud83d\ude00\u0107\u00e7 \n hello

print('\ud83d\ude00\u0107\u00e7 \n hello') #produces wanted result

我希望结果看起来像这样:

奇克

你好

a = "\ud83d\ude00\u0107\u00e7 \n hello"

 a.encode('utf-16', 'surrogatepass').decode('utf-16')    

输出:

'ćç \n hello'

经过又一个小时的反复试验,我发现答案是这样的:

line.encode('utf-8').decode('unicode-escape')