如何在 Python 中將 \\ 替換為 \?


有兩種方法可以用 Python 來替換 \ 或去掉轉義的反斜槓的字串。第一個方法是利用 literal_eval 來對字串進行評估。請注意,使用此方法需要在另一個層的引號中將字串括起來。例如

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

另一種方法是從字串類使用 decode('string_escape') 方法。例如,

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

更新於: 2019-09-30

673 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.