3

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

2 Answers 2

3

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.
Sign up to request clarification or add additional context in comments.

3 Comments

I like this answer because it could be adapted pretty easily to handle decimals as well.
What exactly does the above regex statement mean and how does it work? Does it account for different types of punctuation, non-numerics, etc.?
(\d+) finds ints in the string. And then it is multiplied by the required number
2

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.

1 Comment

What exactly does the above regex statement mean and how does it work? Does it account for different types of punctuation, non-numerics, etc.?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.