有没有办法在strip方法中使用regex模式

2024-10-04 07:30:23 发布

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

我有一个这样的字符串列表

...

'43.990\none of the things we notice\nis that the headers all have\n\n296\n',
'47.020\nthe word edit and\nbraces behind them,\n\n297\n',

...

我只需要上面列表中的文本,而不需要起始数字和\n。有没有像这样的正则表达式模式

i.strip(r"[0-9.\\n]+")

这似乎不起作用


Tags: ofthe字符串none列表thathaveall
2条回答

我将使用:

inp = ['43.990\none of the things we notice\nis that the headers all have\n\n296\n', '47.020\nthe word edit and\nbraces behind them,\n\n297\n']
output = [re.sub(r'\s*\d+(?:\.\d+)?\s*', ' ', x).strip() for x in inp]
print(output)

这张照片是:

['one of the things we notice\nis that the headers all have',
 'the word edit and\nbraces behind them,']

您可以使用re.sub替换与正则表达式匹配的字符,并在行的开头和结尾加上锚:

i = re.sub('^[0-9.\n]+|[0-9.\n]+$', '', i, re.I)

输出(对于两个样本数据):

one of the things we notice
is that the headers all have
the word edit and
braces behind them,

注意:我假设数据中的\n是一个实际的换行符,如果不是(它是文字字符串\n),则应该使用以下内容:

i = re.sub(r'^(?:[0-9.]|\\n)+|(?:[0-9.]|\\n)+$', '', i, re.I)

输出:

one of the things we notice\nis that the headers all have
the word edit and\nbraces behind them,

相关问题 更多 >