Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Thay thế \\ bằng \ trong Python

Có 2 cách thay \\ bằng \ hoặc unescape backslash-escaped string trong Python. Cách 1: dùng literal_eval evaluate string. Lưu ý: cần wrap string trong layer quote khác. Ví dụ:

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

Cách 2: dùng method decode('string_escape') từ class string. Ví dụ:

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