python

String formation and interpolation using Python

We can format our string with variable appends to the string in python. There are many ways of string interpolation in python. We are listing them here one by one.

str_1 = "Hello"
str_2 = "Devsheet"

#Using .format() method
#Using blank curly brackets
new_str_1 = "Welcome User {} from {}".format(str_1, str_2)
print(new_str_1)
# -> Welcome User Hello from Devsheet

#Using variable names
new_str_2 = "{s1} from {s2}.".format(s1=str_1, s2=str_2)
print(new_str_2)
# -> Hello from Devsheet.

We have two variables str_1 and str_2 contain different string values in the above code snippet and we are spending them in a new string and making a new string. For this, we are using the .format() method of a python string.

String Interpolation using .format() method

String formation using .format() is a highly used and simplest method to make our desired string from different variable values append in the new string. You can directly use the .format() method after string and pass variable names inside the format() method.

You need to place blank curly brackets or curly brackets with variable names inside the string where you want to append the variable value.

Format string using blank curly brackets and .format() method

If you want to use python variables into a string without initializing any variable inside the format() method you can use blank curly brackets where you want to show the variable value. Below is the string example.

part_1 = "String part 1"
part_2 = "String part 2"

concatenated_str = "Part 1: {}. Part 2: {}".format(part_1, part_2)
print(concatenated_str)
# -> Part 1: String part 1. Part 2: String part 2

Format string using variables names initialized inside format method

You can create variables inside the format() method of python string and use them in the string with curly brackets where you want to show its value.

first_name = "Rick"
last_name = "Grimes"

full_name = "My Name is: {fname} {lname}".format(fname=first_name, lname=last_name)
print(full_name)
# -> My Name is: Rick Grimes
name = "Daryl"
place = "Alexendria"

info_str = f"My name is {name}. I live at {place}"
print(info_str)
# -> My name is Daryl. I live at Alexendria
You can use f keyword before the string to tell that we are going to format it. In the above code example, we have two python variables name and place. We are using them in making our string and assigning the final string to the info_str variable.
Was this helpful?