python - 在 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)
解决方案
您可以在此处使用正则表达式。
前任:
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.
推荐阅读
- android-studio - 'pub get' 尚未在 android studio 中运行
- docker - socket.io 如何处理 docker 部署的多个实例?
- java - 我们可以使用 Firebase 的 UID 而不是注册令牌在 android 中发送通知吗?
- java - 在JUNIT json字符串中获取错误无法识别的字符转义'S'
- python-3.x - 根据列值python制作dtaframe的子集
- python - 现有 Oracle 表上的 Django 模型设置
- spring-boot - Spring Boot webflux TEXT_EVENT_STREAM_VALUE 不起作用
- python - 修改神经网络以一次预测 3 个示例
- karate - 如何在空手道中为 SOAP 创建动态有效负载
- python - Groupby 并在 PySpark 数据框中创建一个新列