String interpolation is a process of injecting value into a placeholder in a string literal. It helps in dynamically formatting the output. A placeholder is a variable to which you can assign data/value later. Python supports following ways for string interpolation
- str.format()
- f-string
- Template String
str.format()
Str.format() is used for positional formatting. { } is used as a placeholder and value passed by method .format() will be replaced by { }, the rest of the string literals will be unchanged in the output. It allows re-arranging the order of placeholders within string literals without changing the order they are listed in .format().
Below example shows the string formatting using .format(). For more details refer to this link.
# Default(implicit) order default_order = "{}, {} and {}".format('IN','BL','SE') print(default_order) # Output: IN, BL and SE # Order using positional argument positional_order = "{1}, {0} and {2}".format('IN','BL','SE') print(positional_order) # Output: BL, IN and SE # Order using keyword argument keyword_order = "{s}, {b} and {j}".format(j='IN',b='BL',s='SE') print(keyword_order) # Output: SE, BL and IN
f-String
f-string or formatted string literal provides a way of formatting strings using a minimal syntax.‘f’ or ‘F’ is used as a prefix and {} are used as placeholders. A f-string must start with prefix f. Unlike .format( ), f-string doesn’t allow empty braces {}. We can embed arbitrary Python expressions, and even can do inline arithmetic with it.
name = 'World' program = 'Python' print(F'Hello {name}! This is {program}') # Output # Hello World! This is Python
In above example literal prefix f tells Python to restore the value of string variables inside braces {}. Following example shows the application of f-string using python data structures.
from datetime import datetime today=datetime.now() #List info=["Om",33] print(f"{info[0]} is {info[1]} years old") # Output # Om is 33 years old #Dictionary data= dict(name="Om", age=33) print(f"{data['name']} is {data['age']} years old ") # Output # Om is 33 years old # Custom formatting print(f"Date in default format: {today} ") # Output # Date in default format: 2020-09-14 17:52:59.574983 print(f"Date in custom format: {today:%d/%m/%y}") # Output # Date in custom format: 14/09/20
Template String
Template strings provide simpler syntax and functionality. A primary use case for template strings is for internationalization. It support $-based substitutions, using the following rules:
- $$ is an escape; it is replaced with a single $.
- $identifier names a substitution placeholder matching a mapping key of “identifier”. Identifier is restricted to any case-insensitive ASCII alphanumeric string (including underscores). The first non-identifier character after the $ character terminates this placeholder specification.
- ${identifier} is equivalent to $identifier. It is required when valid identifier characters follow the placeholder but are not part of the placeholder i.e. “${identifier}NonIdentifier”.
Identifier is used to map the replacement keywords specified in method substitute( ) or safe_substitute( ). Mapping is any dictionary-like object with keys that match the placeholders in the template. Alternatively, keyword arguments can be used, where the keywords are the placeholders.
- substitute(mapping={}, /, **kwds) : Return a new string after template substitution. When both mapping and kwds are given and there are duplicates, the placeholders from kwds take precedence.
- safe_substitute(mapping={}, /, **kwds) : Similar to substitute(), except that if placeholders are missing from mapping and kwds, the original placeholder will appear in the resulting string intact. It always tries to return a usable string instead of raising an exception.
Below example shows the usage of above functions.
#4.Using Template string from string import Template # Creating object of Template class person_info = Template('\n$name is $years years old!') # Using substitute() print(person_info.substitute(name='Om',years=33)) info = {'name':'Om','years':33} # Using safe_substitute() print(person_info.safe_substitute(info))