如何用小数号列表替换字符串中的小数号列表?
我需要用另一个小数号列表替换字符串中的小数号列表。以下是第一次尝试,该尝试更改所有小数号的十进制数字:
>>> re.sub (r"[-+]?\d*\.\d+f?", "1.0", "hello 1.2 3.4")
'hello 1.0 1.0'
我需要诸如my_replace
下面的内容:
>>> my_replace (r"[-+]?\d*\.\d+f?", [1.0, 2.0], "hello 1.2 3.4")
'hello 1.0 2.0'
如何使用Python的RE模块实现my_replace
?
I need to replace the list of decimal numbers in a string with another list of decimal numbers. The following is a first try, that changes all decimal numbers with the same decimal number:
>>> re.sub (r"[-+]?\d*\.\d+f?", "1.0", "hello 1.2 3.4")
'hello 1.0 1.0'
I need something like my_replace
below:
>>> my_replace (r"[-+]?\d*\.\d+f?", [1.0, 2.0], "hello 1.2 3.4")
'hello 1.0 2.0'
How can i implement my_replace
with python's re module?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您不能将列表用作替换变量并在它们上迭代。因此,它无法处理不可用的对象(这是Python抱怨的)。但是它也能够处理数字(所以它需要一个字符串列表,但这显然是假设的XD),
我只会循环绕字符串,并兼容所有不是十进制数字的所有内容找到十进制数字。
将其包装到函数,并且您的
my_replace()
=)I don't think that you can use a list as replacement variables and iterate over them. So it can't handle unhashable objects (this is what python is complaining about). But it wouln'd be able to handle numerics as well (so it would need a list of strings but this is obviously hypothetical xD)
I would just loop over the string and compy everything that is not a decimal number to a new string and replacing the decimal numbers found.
Wrap it to a function and you have your
my_replace()
=)