[英]Removing these trailing characters from text in Python
我正在處理 Python 中的文本並嘗試刪除尾隨字符。 我知道rstrip
function 但不幸的是,由於(我認為)尾隨字符的性質,它沒有擺脫尾隨字符。 下面是一個最低限度可重現的示例,非常感謝您的幫助。
x="test string\\r\\n\\"
x.rstrip()
結果我需要得到的是“文本字符串”,但我得到的是test string\\r\\n\\
換句話說,沒有任何內容被刪除。
請指教。 先感謝您。
是這樣的嗎?
# Note this is an ordereddict (default in Py3.8+)
mapping = {
r'\\r': '\r',
r'\\n': '\n',
r'\\': '\\' # keep this line last
}
def unescape(escaped_string):
t = escaped_string
for s, r in mapping.items():
if s in t:
t = t.replace(s, mapping[s])
return t.strip()
使用示例
x = r"test string\\r\\n\\"
y = unescape(x)
print("Str with escaped chars")
print(f" in: '{x}'")
print(f" repr(in): {repr(x)}")
print("\nStr with unescaped chars")
print(f" out: '{y}'")
print(f"repr(out): {repr(y)}")
print("\nStripped and unescaped")
fin = y.replace('\\','').strip()
print(f" stripped: {repr(fin)}")
結果
Str with escaped chars
in: 'test string\\r\\n\\'
repr(in): 'test string\\\\r\\\\n\\\\'
Str with unescaped chars
out: 'test string
\'
repr(out): 'test string\r\n\\'
Stripped and unescaped
stripped: 'test string'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.