![](/img/trans.png)
[英]How do I avoid an escape character in a dynamically assigned string in python?
[英]How do I use string formatting with explicit character escape codes in Python?
我知道我可以打印以下內容:
print u'\u2550'
我該如何使用.format
字符串方法呢? 例如:
for i in range(0x2550, 0x257F):
s = u'\u{04X}'.format(i) # of course this is a syntax error
您正在尋找unichr()
函數 :
s = u'{}'.format(unichr(i))
或只是普通
s = unichr(i)
unichr(integer)
為給定的代碼點生成一個unicode字符。
\\uxxxx
語法僅適用於字符串文字 ; 這些在運行代碼之前由Python編譯器處理。
演示:
>>> for i in range(0x2550, 0x257F):
... print unichr(i)
...
═
║
╒
╓
╔
╕
╖
# etc.
如果您的字符串中確實有文字\\uxxxx
序列,您仍然可以讓Python使用unicode_escape
編解碼器將它們轉換為Unicode字符:
>>> print u'\\u2550'
\u2550
>>> print u'\\u2550'.decode('unicode_escape')
═
>>> print '\\u2550'.decode('unicode_escape')
═
>>> '\\u2550'.decode('unicode_escape')
u'\u2550'
在Python 2中,您可以在字節字符串和unicode
字符串值上使用此編解碼器。 輸出始終是unicode
字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.