Print Formatting

Often you will want to “inject” a variable into your string for printing. Something like this :

mystr = "dog"  print("i love my " + mystr)

Here we simply performed a string concatenation However there are more effective ways of doing the same with a lot of options. We will be covering two ways to format strings to print variable in them. This is also called String interpolation.

  • format() method
  • f-string(formatted string literals)
format() method

The format() formatting follows the following syntax:

  • “this is String {} and this is string {}”.format( “one” , “two”)

When you actually print the above code , in place of the first { } you will see “one” and in place of second { } , you will see “two”. So the actual output will be ” this is string one and this is string two”. Note that index of objects within the format() method can easily be specified so that they appear in that specified order within the { } when printing the string. Let us understand this with an example.

output :
python is fun  this man healthy is  this man is healthy
(variable , value) pair in format() method

Usage of (variable , value) pair in the format() method increases the overall readability of the code. When using (variable , value) pair in .format() method, you assign a variable to a value and than to print a value in place of { } you need to place the corresponding variable within the { }. Let us understand this with an example.

In the code below i am printing “python the coding superpower”as the resultant string. I will make the following (variable , value) pairs :

  • p = ‘python’
  • t = ‘the’
  • c = ‘coding’
  • s = ‘superpower’

format() syntax for floating point numbers

format() method allows us to set the width and precision of a floating point number. The Variation in width of a number results in addition or removal of whitespaces while precision allows us to set the number of numbers after decimal point. Say there is a number 3.14159 and we want to reduce it to three places after decimal , To do this we can set the precision as 3f and get the required result as 3.141.The syntax looks something like this:

  • “I am a string {v:width.precision f }”.format(v = value)

f-string method is also very similar to .format() method. Here instead to writing .format() to assign values to variables , we will be using f’my_string’ or F’my_string’.You can also use ” ” instead of ‘ ‘.

language = 'python'  site = 'py4u'  print(f'i learn {language} on {site}.org')

output :
i learn python on