String interpolation in python 3
In this chapter, you will learn about, string interpolation in python 3. String interpolation is nothing but formatting a string with printing the dynamic values in it. For example, you may want to print a sentence that greets an employee with their names.
In python you can use the two major string functions for formatting the text or sentence, they are
- format()
- f-strings
format():
Now let’s see the method format() in detail, the syntax of a format() method is as follows. Let’s see a basic example of string formatting by using the method format().
print('Hi {} good morning...'.format('John')) # Output # Hi John good morning...
There are some advantages of format() method when you compare it to the other string formatting methods. Now let’s see the advantages of the format method.
Variables can be inserted by using the index positioning:
Let’s say you need to send an email to the employee with his task details,
print('Hi {} good morning, your today task ticket no is {}, and the timeline duration is {}'.format('John','JIRA-123','2 days')) # Output # Hi John good morning, your today task ticket no is JIRA-123, and the timeline duration is 2 days
If you observe the print statement, the python is inserted into an ordered string in the print string. We can change the order of variables with the help of index values. Let’s see an example.
print('Hi {0}, you have time duration of {2} for the task {1}'.format('John','JIRA-123','2 days')) # Output # Hi John, you have time duration of 2 days for the task JIRA-123
Variables can be inserted by using the keyword:
format method also supports the keywords which can be used to assign particular value with the combination of the keyword.
print('Hi {name}, you have time duration of {timeLine} for the task {task}'.format(name='John',task='JIRA-123',timeLine='2 days')) # Output # Hi John, you have time duration of 2 days for the task JIRA-123
Float formatting:
The format method can also be used for formatting the floating-point values, let see an example for the same.
print('Hi {name}, your salary for the month is {salary:5.2f}'.format(name='John', salary=float(45000.56784444444444))) # Output # Hi John, your salary for the month is 45000.57
f-strings:
Now we will look into the other string formatting method which is f-strings. The f-strings method is very easy to use, as it has simple syntax and variables can be injected very easily. the f-strings has been introduced in python 3.6, Let’s see an example
name= 'John' task = 'JIRA-1234' timeLine = '2 days' print(f'Hi {name}, your task is {task} and duration is {timeLine}') # Output # Hi John, your task is JIRA-1234 and duration is 2 days
One thought on “String interpolation in python 3”
Comments are closed.