String Interpolation in Python
String Interpolation
String interpolation is a process of injecting value into a placeholder (a placeholder is nothing but a variable to which you can assign data/value later) in a string literal. It helps in dynamically formatting the output in a fancier way. Python supports multiple ways to format string literals.
Ways of String Interpolation
- %-formatting
- str.format()
- Template Strings
- F-strings
%-formatting –
- In python modulo(%) operator is overloaded in str class to perform string formatting.
- If we have lots of variable to concat , then we can use %-formatting.
code 1:
Run
# Python program to demonstrate # string interpolation n1 = 'Hello' n2 ='PrepInsta' # for single substitution print("Welcome to % s"% n2) n3='Prepsters' # for single and multiple substitutions () mandatory print("% s % s welcome to %s."%(n1, n3,n2))
Output:
Welcome to PrepInsta
Hello Prepsters welcome to PrepInsta.
Str.format()
- It is one of the string formatting methods in Python3.
- It is used for positional formatting, this allows re-arranging the order of placeholders within string literals without changing the order they are listed in .format( ).
Code 2:
Run
# Python program to demonstrate # string interpolation n1 = 'Hello' n2 ='PrepInsta' # for single substitution print("Welcome to {}" .format(n2)) n3='Prepsters' # for multiple substitutions print("{b1} {b2} welcome to {b3}.".format(b1=n1, b2=n3,b3=n2))
Output:
Welcome to PrepInsta
Hello Prepsters welcome to PrepInsta.
Template Strings
- It lets you make substitutions in a string using a mapping object.
- Here, a valid python identifier preceded by sign ‘$’ is used as a placeholder.
Code 3:
Run
# Python program to demonstrate # string interpolation from string import Template n1 = 'Hello' n2 ='PrepInsta' # made a template which we can we use p=Template('Welcome to $s2') print(p.substitute(s2=n2)) n3='Prepsters' p1=Template('$s1 $s2 Welcome to $s3.') print(p1.substitute(s1=n1, s2=n3,s3=n2))
Output:
Welcome to PrepInsta
Hello Prepsters Welcome to PrepInsta.
F-strings
- F-strings provide a way to embed expressions inside string literals, using a minimal syntax.
- In Python source code, an f-string is a literal string, prefixed with ‘f’, which contains expressions inside braces.
Code 4:
Run
# Python program to demonstrate # string interpolation from string import Template n1 = 'Hello' n2 ='PrepInsta' # for single substitution print(f"Welcome to {n2}") n3='Prepsters' print(f"{n1} {n3} welcome to {n2}.")
Output:
Welcome to PrepInsta
Hello Prepsters welcome to PrepInsta.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment