Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Unescape Backslash-escaped String ใน Python

มี 2 วิธีหลัก:

1. ใช้ ast.literal_eval()

ต้องห่อสตริงด้วย quote เพิ่มอีกชั้น

>> import ast
>>> a = '"Hello,\\nworld"'
>>> print(ast.literal_eval(a))
Hello,
world

2. ใช้ decode('string_escape') (Python 2)

>> print("Hello,\\nworld".decode('string_escape'))
Hello,
world

หมายเหตุ: ใน Python 3 ให้ใช้ bytes(s, 'utf-8').decode('unicode_escape')