How to add a number into a string in python 3 ?


Examples of how to combine a number into a string in python 3:

Convert the number to a string

A straightforward solution is to convert the number to a string using str():

weight = 95.5

s = "my weight is " + str(weight) + "kg"

returns

'my weight is 95.5kg'

Format the number using str.format()

Another better approach is to use str.format():

weight = 95.5

s = "my weight is {}kg".format(weight)

also returns

'my weight is 95.5kg'

Format() has many advantages, you can for example insert multiple numbers:

year = 1982
month = 7
day = 8

s = "My date of birth is {}-{}-{}".format(year,month,day)

returns

'My date of birth is 1982-7-8'

Here, lets see some of the most used features:

Round a float number

weight = 95.5

s = "my weight is {:.0f}kg".format(weight)

returns

'my weight is 96kg'

Add leading zeros in front of the numbers

year = 1982
month = 7
day = 8

s = "My date of birth is {}-{:02d}-{:02d}".format(year,month,day)

returns

'My date of birth is 1982-07-08'

Format a float number

import math

pi = math.pi

pi

s = 'PI value is : {}'.format(pi)

returns

PI value is : 3.141592653589793

s = 'PI value is : {:0.2f}'.format(pi)

returns

PI value is : 3.14

s = 'PI value is : {:0.4f}'.format(pi)

returns

PI value is : 3.1416

s = 'PI value is : {:6.4f}'.format(pi)

returns

PI value is : 3.1416

s = 'PI value is : {:10.4f}'.format(pi)

returns

PI value is :     3.1416

Summary table

Input Format Output
95.5 :.0f 96
8 :02d 08
8 :04d 0008
3.141592653589793 3.141592653589793
3.141592653589793 :0.2f 3.14
3.141592653589793 :0.4f 3.1416
3.141592653589793 :6.4f 3.1416
3.141592653589793 :10.4f 3.1416

References