Formatting a python string is basic operation in python, especailly when you want to print a string, we have two ways to format a string. In this tutorial, we will introduce this two methods to format a string.
Use “%” operator
Here is “%” operator list.
%s – String (or any object with a string representation)
%d – Integers
%f – Floating point numbers
%.<number of digits>f – Floating point numbers with a fixed amount of digits to the right of the dot.
%x/%X – Integers in hex representation (lowercase/uppercase)
So we can use these operator to format a python string.
Format a string
name = 'tutorialexample.com' str_1 = 'my name is %s' % name print(str_1)
Output is: my name is tutorialexample.com
Format an integer
age = 12 str_1 = 'my age is %d' % age print(str_1)
Output: my age is 12
Format a float
score = 96.5 str_1 = 'my score is %.1f' % score print(str_1)
Output: my score is 96.5
Use string format() function
Here is an example.
name = 'tutorialexample.com' str_1 = 'my name is {}'.format(name) print(str_1) age = 12 score = 96.5 str_1 = 'my age is {} and score is {}'.format(age, score) print(str_1)
The output is:
my name is tutorialexample.com my age is 12 and score is 96.5
Notice: if you use format() function to format a string, you must nocie the variable order.