If I have a string where I want to perform the same operation multiple times but change something about it each time, is this possible? For example, 'The person is 13 years old' and I want to increment '13' to 14, 15, 16, 17, etc. every time I run the loop, and then do use that new string in my operation.
Any help is appreciated.
Add a comment
|
3 Answers
Use a for loop:
x = 'The person is %s years old'
num = 13
lst = []
for i in range(5):
lst.append(x % num)
num += 1
print (lst)
This will print:
['The person is 13 years old', 'The person is 14 years old', 'The person is 15 years old', 'The person is 16 years old', 'The person is 17 years old']
Comments
You can use a for-loop
for i in range(13, 20):
print("The person is", i, "years old")
This will print:
The person is 13 years old
The person is 14 years old
The person is 15 years old
The person is 16 years old
The person is 17 years old
The person is 18 years old
The person is 19 years old
Comments
You can use regular expressions to extract the age, increment it, and replace it on the original string, something like the following:
import re
pattern = re.compile('\d+')
string = 'Some long text informing John Doe is currently 15 years old'
some_condition = True
while some_condition: # replace your loop condition here
match = re.search(pattern, string)
if match:
match = int(match.group())
if match > 50: # arbitrary condition just to break the loop
some_condition = False
else:
match += 1
string = re.sub(pattern, str(match), string)
print(string)