Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

Increment a number value contained within a string using a loop (Python)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...