python - 如何对Python中的一组字符正确使用 "Replace"方法

标签 python replace

import re

words = ['Duration12:1', 'Noun', 'Adjective7:8']
result = ([re.sub(r'[0-9]+', r'[\g<0>]', w) for w in words])

['Duration[12]:[1]', 'Noun', 'Adjective[7]:[8]']

但现在之后

repResult = [x.replace(':[%d]', ':%d') for x in result]

我又开始了

['Duration[12]:[1]', 'Noun', 'Adjective[7]:[8]']

虽然我希望替换应该是的字符

['Duration[12]:1', 'Noun', 'Adjective[7]:8']

这里使用该方法的语法正确还是我遗漏了什么?

最佳答案

您使用replace是错误的,因为您正在搜索字符串文字“%d”。这不是正则表达式。

您可以像这样修复代码:

import re

words = ['Duration12:14254', 'Noun', 'Adjective7:888']
result = [re.sub(r'[0-9]+', r'[\g<0>]', w) for w in words]
repResult = [re.sub(r':\[(\d+)\]', r':\1', w) for w in result]
print(repResult)

你得到:

['Duration[12]:1', 'Noun', 'Adjective[7]:8']

使用['Duration12:14254', 'Noun', 'Adjective7:888'],您将得到:

['Duration[12]:14254', 'Noun', 'Adjective[7]:888']

可以使用单个正则表达式来简化此代码:

import re

words = ['Duration12:14254', 'Noun', 'Adjective7:888']
result = [re.sub(r'(\d+):(\d+)', r'[\1]:\2', w) for w in words]

关于python - 如何对Python中的一组字符正确使用 "Replace"方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54507475/

相关文章:

vba - EXCEL VBA : How to convert dd/mm/yy into yyyy. mm.dd

mysql - 用通配符替换文本

linux - 跨多个文件增量查找和替换 - Bash

python - 寻找不确定性,减少Python中高斯拟合的卡方

vba - VBA : Search, save and replace by rows according to conditions

python - 具有动态属性的 Django 模型

Python- select() 是否可以与 UDP 函数(recvfrom() 和 sendto() )一起使用?

java - 使用 Replace 方法查找字符串中字符的计数

python - 主机中任务的指派/分配

python - 更快的解析 .pcap 的方法