如何使用正则表达式和列表替换特定位置?
可以说,我在Python中有以下字符串:
s = "Hi, I currently have 2 apples and 3 oranges"
在正则我们可以做的
r = re.findall(r'\d',s)
,这将为我们提供一个包含数字的列表: [“ 2”,“ 3”]
但是,可以说我想使用列表中出现在句子中的顺序替换这些数字。
new_list = ["4","5"]
并做新句子说:
“嗨,我目前有 4 苹果和 5 oranges
我尝试执行以下操作:
new_sentence = [re.sub(('\d'),x, s) for x in new_list]
但这给了我:
['Hi, I currently have 4 apples and 4 oranges', 'Hi, I currently have 5 apples and 5 oranges']
这不是我想要的。您如何使用正则列表使用列表出现的顺序替换值?
lets say I have the following string in Python:
s = "Hi, I currently have 2 apples and 3 oranges"
in regex we can do
r = re.findall(r'\d',s)
and this would give us a list containing the numbers:["2","3"]
However, lets say I want to substitute these numbers using a list in the order that they appear in the sentence.
new_list = ["4","5"]
and make the new sentences say:
"Hi, I currently have 4 apples and 5 oranges"
I tried doing the following:
new_sentence = [re.sub(('\d'),x, s) for x in new_list]
But that gave me:
['Hi, I currently have 4 apples and 4 oranges', 'Hi, I currently have 5 apples and 5 oranges']
Which is not what I wanted. How do you substitute values using regex in the order that they appear using a list?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以从
new_list
中制作迭代器,并在re.sub
中使用它:打印:
You can make an iterator from the
new_list
and use it inre.sub
:Prints:
这是另一种解决方案
当map接收到这样的多个iterables时,它首先将两个iterables中的第一个项目作为参数发送到
operator.add
函数,然后是接下来的两个项目,依此类推。我们必须在替换值的末尾添加一个空字符串,以使其与re.split
的长度相同。Here is another solution
When map receives multiple iterables like this, it starts by sending the first item from the two iterables as parameters to the
operator.add
function, and then the next two items, and so on. We have to add an empty string to the end of the replacement values to make it the same length asre.split
.