如何使用正则表达式和列表替换特定位置?

发布于 2025-01-18 02:23:01 字数 684 浏览 2 评论 0原文

可以说,我在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

幸福%小乖 2025-01-25 02:23:01

您可以从new_list中制作迭代器,并在re.sub中使用它:

import re


s = "Hi, I currently have 2 apples and 3 oranges"
new_list = ["4", "5"]

new_list_iter = iter(new_list)

out = re.sub(r"\d+", lambda _: next(new_list_iter), s)
print(out)

打印:

Hi, I currently have 4 apples and 5 oranges

You can make an iterator from the new_list and use it in re.sub:

import re


s = "Hi, I currently have 2 apples and 3 oranges"
new_list = ["4", "5"]

new_list_iter = iter(new_list)

out = re.sub(r"\d+", lambda _: next(new_list_iter), s)
print(out)

Prints:

Hi, I currently have 4 apples and 5 oranges
画尸师 2025-01-25 02:23:01

这是另一种解决方案

''.join(map( operator.add, 
             re.split('\d+', s), 
             ['4','5']+[''] 
))

当map接收到这样的多个iterables时,它首先将两个iterables中的第一个项目作为参数发送到operator.add函数,然后是接下来的两个项目,依此类推。我们必须在替换值的末尾添加一个空字符串,以使其与 re.split 的长度相同。

Here is another solution

''.join(map( operator.add, 
             re.split('\d+', s), 
             ['4','5']+[''] 
))

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 as re.split.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文