Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Format .format to variable

I'm trying to create a function that allows me to pass in a string into an age variable using a while loop. This is the simplified version of the code using the .format string. The following code works as expected.

num = 1
while num<7:
    age = 'My age is {}'.format(num)
    print(age)
    num+=2

The output is as shown below:

My age is 1
My age is 3
My age is 5

However, when I attempt to capture the string 'My age is {}' in the age variable using the while loop it doesn't work. Here is the code.

num = 1
age = 'My age is {}'
while num<7:
    age = age.format(num)
    print(age)
    num+=2

I get the following output.

My age is 1
My age is 1
My age is 1

Any idea the reason the num does not increment in the while loop in the second example? What's the solution?

like image 476
Zach Avatar asked Jan 02 '23 05:01

Zach


2 Answers

You're overwriting the age string so there's nothing left to format in the second iteration. You could use two strings - one with the template to format in to, and one with the formatted result:

num = 1
template = 'My age is {}'
while num<7:
    age = template.format(num)
    print(age)
    num+=2
like image 69
Mureinik Avatar answered Jan 05 '23 05:01

Mureinik


The first time through the loop, you've replaced the {} in the string with a number. From that point forward, format doesn't have anything to do since the string doesn't have any formatting markers in it.

like image 34
Mark Ransom Avatar answered Jan 05 '23 05:01

Mark Ransom