gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:32:04 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com