首页 > 解决方案 > 在 Python 字符串中仅乘以数值

问题描述

我有兴趣将 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)

标签: pythonpython-3.x

解决方案


您可以在此处使用正则表达式。

前任:

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.

推荐阅读