atlanticpacificsky
atlanticpacificsky

Reputation: 31

Multiply Only Numeric Values in Python String

I am interested in multiplying all the numbers in a Python string by a variable (y) as in the following example where 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."

I tried the following Python code, but am not getting the desired output. How can I create the desired output in Python code?

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)

Upvotes: 3

Views: 185

Answers (2)

Selcuk
Selcuk

Reputation: 59425

You can use a regular expression:

import re
print(re.sub("(\d+)", "\g<1>0", string_init))

this should print:

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

Upvotes: 2

Rakesh
Rakesh

Reputation: 82785

You can use regex here.

Ex:

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))

Output:

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

Upvotes: 3

Related Questions