String Formatting in Python

What is String Formatting?

String formatting is appealingly designing your string using formatting techniques gave by the specific programming language. We have diverse string arranging procedures in Python. We are presently going to investigate the new f-string formatting technique.

f-string assesses at runtime of the program. It’s quick compared to the previous methods.

f-string having a simple syntax compared to the previous string formatting methods of Python. We will investigate all of this using different examples.

Syntax of String formatting


In place of string, we can use our own string.

How to format string in Python?

The format() method formats the predefined value(s) and inserts them inside the string’s placeholder.

The placeholder is defined utilizing curly braces: {}.

The format() method returns the formatted string.

Syntax of formatting string using format() is:


where at least one value that ought to be formatted and inserted in the string. The values can be A number indicating the position of the element you need to remove.

The values are either a list of values isolated by commas, a key=value list, or a blend of both.

The values can be of any data type.

The Placeholders

The placeholders can be identified using named indexes {price}, numbered indexes {0}, or even empty placeholders {}.

Let’s understand with the help of examples:

str1 = "I am studying {}".format("Python")
str2 = "My name is {}, I am {} years old".format("Joseph",21)


Single Formatter

This implies we pass just a single parameter inside the format function which puts the value passed as a parameter in the placeholder position. The placeholder position is represented by curly braces. Since we are passing just a single parameter inside the format function. It is known as a single formatter.

str = "13 reasons {}"

print("Sherlok Holmes deduces that the deaths are actually {}".format("murders"))


Multiple Formatters

For this situation, the formatting method will have more than one parameter in it. This sort of formatting is used when we need to accomplish more than one variable substitution in the current string. We should put additional placeholders in the string if we need to accomplish more than one variable replacement. The placeholders will be replaced by values in order.

str = "Joseph is a nice {} and he is a {}"

print("This will be of {} help to the {}".format("great","students"))


Formatters with positional and keyword arguments

This is an interesting method of formatting using the string formatter. To comprehend this we should understand that values set as parameters inside the formatter function have tuple as their data type which implies they can be independently called using their index number beginning from zero. These index numbers can be passed in the placeholders of the original string and dependent on the index number the values will be substituted in the placeholders.

print("{0} is studying {1}!!".format("John","Physics"))

print("{1} is a school {0}!!".format("teacher","Berlin"))

print("{name} is the capital of {0}!!".format("Bangalore",name ="Karnataka"))


Index Error

It is imperative to talk about this as we should remember that there is something we get as an index error when the number of placeholders passed in a string doesn’t coordinate with the number of parameters inside the function. So we would, for instance, get index error if we have three placeholders for two parameters in the format method.

str = "Rahul is a {} and he is {},{}"


Different Formatting Types are as follows:

Displaying Variables

We already use the str.format() method for the most part to format the strings. In any case, the time has transformed we have another method to make our attempts twice as fast.

The variables in the curly { } braces are shown in the output as a normal print statement. Let’s understand with the help of an example.

sub = "Python"
info = "interpreted, high level"

print(f"{sub} is an {info} language.")


sub = "Python"
info = "interpreted, high level"

print(F"{sub} is an {info} language.")


We can see that it will work the same whether it is in lowercase or uppercase.


We can evaluate expressions like arithmetic, a function call, and so on in a string. f-string allows us to evaluate expressions.

Just put the expression inside {} curly braces and remember f-string evaluates during the runtime.

print(f"{20 * 5}")

def greet(name):
    return "Hello, " + name
## calling the function using f-string
name = "Codedec"

string = "codedec is an educational company."


Special Characters

We can use any quotation marks {single or double or triple} in the f-string. We have to use the escape character to print quotation marks. The f-string expression doesn’t allow us to use the backslash. We have to place it outside the { }.

We can also have a double set of braces to print the braces{} using f-string. 

name = "Bad"

## displaying single quotations
print(f"Breaking \'{name}\'")


## displaying double quotations
print(f"Breaking \"{name}\"")




Now, lets understand string formatting with the help of an example:

Given an integer, n , print the following values for each integer i from 1 to n:

1. Decimal
2. Octal
3. Hexadecimal (capitalized)
4. Binary
The four values must be printed on a single line in the order specified above for each i from 1 to n. Each value should be space-padded to match the width of the binary value of n.

Input Format

A single integer denoting n.


1<= n <= 99

Output Format

Print n lines where each line i (in the range 1 <= n <= 99) contains the respective decimal, octal, capitalized hexadecimal, and binary values of i. Each printed value must be formatted to the width of the binary value of n.

def print_formatted(number):
    align = len(bin(number)[2:])
    for num in range(1, number + 1):
        n_dec = str(num)
        n_oct = oct(num)[2:]
        n_hex = hex(num)[2:].upper()
        n_bin = bin(num)[2:]
        print(n_dec.rjust(align), n_oct.rjust(align), n_hex.rjust(align), n_bin.rjust(align))
if __name__ == '__main__':
    n = int(input())