我感兴趣的是将 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/