【问题标题】:String contains unicode and so it cannot get printed which results in UnicodeDecodeError字符串包含 unicode,因此无法打印,导致 UnicodeDecodeError
【发布时间】:2021-05-25 00:16:59
【问题描述】:

我正在尝试在 Python 2.7 中打印一个字符串,但该字符串包含字符“(150\xb5s)”,它无法打印 x5bs,因此该字符串的位置会出错。

UnicodeEncodeError: "ascii" codec can't encode character u'\xb5' 
string_print = "29 days in (F150\xb5s)"
with open("testing_file.txt", "w") as fill:
    fill.write(string_print)

我尝试从 stackoverflow 解决方案中执行此操作,但仍然遇到相同的错误

string_print = "29 days in (F150\xb5s)"

with open("testing_file.txt", "w") as fill:
    fill.write(string_print.decode("utf-8"))

使用原始字符串方法可行,但问题是 string_print 可以包含任何字符串,因为我只是将一个很长的程序缩短以更好地隔离问题。那么有没有办法让变量 string_print 成为原始字符串的一部分。如果我只做“(F150\xb5s)中的29天”的原始字符串,它就可以工作。

r"29 days in (F150\xb5s)"

但是 string_print 可以有任何类型的字符串

【问题讨论】:

标签: python python-2.7 ascii unicode-string


【解决方案1】:

我已经找到了解决这个问题的方法。基本上我们可以使用 repr(string_print) 来解决这个问题。

string_print = "29 days in (F150\xb5s)"
with open("testing_file.txt", "w") as fill:
    fill.write(repr(string_print))

【讨论】:

    猜你喜欢
    • 2015-11-16
    • 2019-04-26
    • 1970-01-01
    • 2020-11-27
    • 2022-01-25
    • 2013-05-09
    • 2015-02-23
    • 1970-01-01
    • 2014-08-23
    相关资源
    最近更新 更多