簡體   English   中英

Python如何從字符串中刪除轉義字符

[英]Python how to remove escape characters from a string

我有一個如下所示的字符串,並且我想從Python中的字符串中刪除所有\\ x06字符。

例如:

s = 'test\x06\x06\x06\x06'
s1 = 'test2\x04\x04\x04\x04'
print(literal_eval("'%s'" % s))

輸出:test♠♠♠♠

我只需要字符串測試並刪除所有\\ xXX。

也許正則表達式模塊是要走的路

>>> s = 'test\x06\x06\x06\x06'
>>> s1 = 'test2\x04\x04\x04\x04'
>>> import re
>>> re.sub('[^A-Za-z0-9]+', '', s)
'test'
>>> re.sub('[^A-Za-z0-9]+', '', s1)
'test2'

如果要刪除所有\\xXX字符(不可打印的ASCII字符),最好的方法可能是這樣

import string

def remove_non_printable(s):
    return ''.join(c for c in s if c not in string.printable)

請注意,這不適用於任何非ASCII可打印字符(例如é ,它將被刪除)。

這應該做

import re #Import regular expressions
s = 'test\x06\x06\x06\x06' #Input s
s1 = 'test2\x04\x04\x04\x04' #Input s1
print(re.sub('\x06','',s)) #remove all \x06 from s
print(re.sub('\x04','',s1)) #remove all \x04 from s1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM