Hello Pythonistas, here’s a quick reference to 5 major methods of string formatting in python programming.
Contents
String concatenation
Don’t be scared😰 by the fancy ✨word it just means using the '+'
operator on strings. This example will make it clear:
game = "PUBG"
print(game+" is a game!!")
#!!Don't forget to give a space before 'is' otherwise
#PUBGis a game!! #This will be your ouptut
Output:
PUBG is a game!!
Now, I won’t bore😪 you by saying that with this you can use a variable anywhere in the middle of the string and also at the end and that we can use more than one variable and more than one string.
I know you are smart😎 and curious🤩 enough to try it already.
Print function
This awesome✨ function provides you a facility to print variables, strings, and other data types inside of it by using a ','
comma as a separator. The example below will make it more clear.
show = "Monty Python's Flying Circus,"
print("Python is named after ", show, " a BBC comedy series from the 1970s.")
Output:-
Python is named after Monty Python's Flying Circus, a BBC comedy series from the 1970s.
Format function
It is a special✨ function for using variables in strings. The example below explains how to use it:-
action1 = "Sing"
action2 = "Dance"
action3 = "Be difficult"
print("Three things that python can't do:- {}, {}, and {}!!".format(action1, action2, action3))
#Keyword and position are also possible
Output:-
Three things that python can't do Sing, Dance, and Be difficult!!
You just need to put curly brackets {}
wherever you want to insert a variable then after the string ends use the format function put the values and you are good👍 to go🚶♂️.
using % Operator
This method uses the modulus operator. Wherever in the string, you want to use a variable just put a % there and then write s, d, or f depending on the data type of data in the variable.
%s:- for string data type
%d:- for integer data type
%f:- for float data type
The example below will make it crystal💎 clear:-
name = "Python"
age = 31
number = 284.242
print("I am %s I am %d years old. I support floating point numbers like %f." % (name, age, number))
Output:-
I am Python I am 31 years old. I support floating point numbers like 284.242000 .
F-String: Best For String Formatting
This is our final method it’s pretty easy compared to others while coding something big.
To use this you simply need to put a f
at the beginning of the string and then, wherever you want to use a variable just use it inside curly brackets {variable}
.
what ="f-string"
adjective = "fantastic"
print(f"{what} is {adjective}")
Output:-
f-string is fantastic