python - 仅乘以 Python 字符串中的数值

标签 python python-3.x

我感兴趣的是将 Python 字符串中的所有数字乘以一个变量 (y),如下例中 y = 10。

Initial Input: 
"I have 15, 7, and 350 cars, boats and bikes, respectively, in my parking lot."
Desired Output: 
"I have 150, 70, and 3500 cars, boats and bikes, respectively, in my parking lot."

我尝试了以下 Python 代码,但没有得到所需的输出。如何在 Python 代码中创建所需的输出?

string_init = "I have 15, 7, and 350 cars, boats and bikes, respectively, in my parking lot."

string_split = string.split()
y = 10 
multiply_string = string * (y)
print(multiply_string)

最佳答案

你可以在这里使用正则表达式。

例如:

import re

s =  "I have 15, 7, and 350 cars, boats and bikes, respectively, in my parking lot."
y = 10
print(re.sub(r"(\d+)", lambda x: str(int(x.group())*y), s))
#or 
# print(re.sub(r"(\d+)", lambda x: f"{int(x.group())*y}", s))

输出:

I have 150, 70, and 3500 cars, boats and bikes, respectively, in my parking lot.

关于python - 仅乘以 Python 字符串中的数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63681290/

相关文章:

python - 在不加载对象的情况下从外键字段获取模型实例 ID

python - 如何在 vagrant 的测试中使用命令运行 bash 脚本?

python - 为什么 Python 改变前面有 0 的整数的值?

python - 分隔符长度变化的字符串切片

python - 设计 parking 系统问题输出时出错

python - 如何压缩根据输入选择多少并发任务的代码?

python - 在python 3.4中模拟内部对象的实例方法

python - 如何批量应用map操作?

python-3.x - 从 : h2o. grid.grid_search.H2OGridSearch 获取 H2O 神经网络的结果

python-3.x - Python3中的CSV文件比较算法