使用regex删除hex

2024-09-28 03:17:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从文本字符串中删除一些十六进制(例如\xc3)。 我计划使用正则表达式来帮助消除这些问题。 这是我的代码:

import re
tweet = 'b"[/Very seldom~ will someone enter your life] to question\xc3\xa2\xe2\x82\xac\xc2\xa6"'    
tweet1 = re.sub(r'\\x[a-f0-9]{2}', '', tweet)
print(tweet1)

然而,我并没有删除输出,而是得到了hex的编码版本。以下是我的输出:

^{pr2}$

有人知道我怎样才能去掉那些六角的弦吗?。。。提前谢谢。在


Tags: 字符串代码文本importreyourwill计划
3条回答

你可以试试这样的方法:

import re
import string

tweet = 'b"[/Very seldom~ will someone enter your life] to question\xc3\xa2\xe2\x82\xac\xc2\xa6"'    
tweet1 = re.sub(r'[^\w\s{}]'.format(string.punctuation), '', tweet)
print(tweet1)

输出:

^{pr2}$

正则表达式:

[^\w\s{}]-匹配不是\w\s或标点符号的所有内容。在

在应用regex之后尝试tweet1.decode('ascii','ignore')。在

你可以简单地做

import re
tweet = 'b"[/Very seldom~ will someone enter your life] to question\xc3\xa2\xe2\x82\xac\xc2\xa6"'
tweet1 = re.sub(b'[\xc3\xa2\xe2\x82\xac\xc2\xa6]', '', tweet)

输出:

b"[/Very seldom~ will someone enter your life] to question"

相关问题 更多 >

    热门问题