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

วิธีประมวลผล Escape Sequences ใน String Python

เนื้อหาเหมือน ID 1004108049 (unescape backslash string)

วิธีที่ 1: ast.literal_eval()

>> 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')