![](/img/trans.png)
[英]How do convert unicode escape sequences to unicode characters in a python string
[英]Convert a string with escape sequences to their original character representation in python
假設我有一個程序接收我無法真正控制的輸入。 以下變量按原樣輸入(我們無法在此處更改輸入):
a = "C:\temp"
b = "C:\games"
c = "Hello World"
d = "\t"
不幸的是,Python會誤解事物並放入轉義序列:
In [138]: a[2]
Out[138]: '\t'
In [139]: b[2]
Out[139]: '\\'
In [140]: d[0]
Out[140]: '\t'
假設已經找到答案。 它應該執行以下操作:
def answer(x):
pass #TODO: your code goes here
所需的輸出:
In [200]: answer(a)[2]
Out [201]: '\\'
In [202]: answer(a)[3]
Out [203]: 't'
In [204]: answer(b)[2]
Out [205]: '\\'
In [206]: answer(b)[3]
Out [207]: 'g'
In [208]: answer(c)
Out [209]: 'Hello World'
我已經嘗試使用ast模塊並使用解碼,但無濟於事:
In [144]: import ast
In [145]: ast.literal_eval(a)
File "<unknown>", line 1
C: emp
^
SyntaxError: invalid syntax
或與解碼:
In [147]: a.decode('string-escape')[2]
Out[147]: '\t'
解決answer()
編輯:“ \\”,而不是[204]示例中的“ \\”
您必須使用encode
而不是decode
:
>>> "\t".encode('string-escape')
'\\t'
您可以使用repr
將此字符串轉換為它們的表示形式,然后剝離'
和"
並使用char:
>>> a = 'C:\temp'
>>> a[2]
'\t'
>>> repr(a).strip('\'"')[2]
'\\'
這個問題的answer
,看起來像
def answer(x): return repr(x).strip('\'"')
如果我理解您的問題,則應使用repr
將字符串轉換為其原始表示形式,然后使用str.partition()
如下例所示:
>>> a = 'C:\temp'
>>> repr(a).partition('\\')
("'C:", '\\', "temp'")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.