簡體   English   中英

字符串包含 unicode ,因此無法打印,導致 UnicodeDecodeError

[英]String contains unicode and so it cannot get printed which results in UnicodeDecodeError

我正在嘗試在 Python 2.7 中打印一個字符串,但該字符串包含字符“(150\xb5s)”並且它無法打印 x5bs,因此它會為字符串的 position 提供錯誤。

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 可以有任何類型的字符串

我找到了解決這個問題的方法。 基本上我們可以使用 repr(string_print) 來解決這個問題。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM