String operations in python, sometimes can be a bit tedious, specially when we need to pass variables within Strings.
Although there are multiple ways to achieve the same, but some of the them are
- String interpolation
- str.format()
Declaring some variables -
Name = 'Python'
Framework = 'Django'
Using str.format()
"Language - {0}, Framework - {1}".format(Name, Framework)
‘Language - Python, Framework - Django’
Using f-strings format - string interpolation
f"Language - {Name}, Framework - {Framework}"
‘Language - Python, Framework - Django’
Handling numeric in Strings
Year = 2015
Month = 12
The following will through an error, as we can use strings and integers without conversions.
"Year is " + Year + ", Month is " + Month
TypeError: can only concatenate str (not "int") to str
The above error can be handled by explicit conversion, str.format and f-strings.
# Explicit conversion to string
"Year is " + str(Year) + ", Month is " + str(Month)
# Using str.format()
"Year is {0}, Month is {1}".format(Year, Month)
# Using f-strings format - string interpolation
f"Year is {Year}, Month is {Month}"
‘Year is 2015, Month is 12’
‘Year is 2015, Month is 12’
‘Year is 2015, Month is 12’
Similarly, mathematical operations can be applied -
Number1 = 2
Number2 = 10
# Using str.format()
print("No. 1 * No. 2 is {0}".format(Number1*Number2))
# Using f-strings format - string interpolation
print(f"No. 1 * No. 2 is {Number1*Number2}")
No. 1 * No. 2 is 20
No. 1 * No. 2 is 20
Notebook Link - String Interpolation in Python