Python 3.6 added a new string formatting approach called
formatted string literals or “f-strings”. This new way of formatting strings
lets you use embedded Python expressions inside string constants. Here’s a simple example to give you a feel for the feature:
>>>
>>> f'Hello, {name}!'
'Hello, Bob!'
As you can see, this prefixes the string constant with the letter “f“—hence the name “f-strings.” This new formatting
syntax is powerful. Because you can embed arbitrary Python expressions, you can even do inline arithmetic with it. Check out this
example:
>>>
>>> a = 5
>>> b = 10
>>> f'Five plus ten is {a + b} and not {2 * (a + b)}.'
'Five plus ten is 15 and not 30.'
Formatted string literals are a Python parser feature that converts f-strings into a series of string constants and expressions.
They then get joined up to build the final string.
Imagine you had the following greet() function that contains an f-string:
>>>
>>> def greet(name, question):
... return f"Hello, {name}! How's it {question}?"
...
>>> greet('Bob', 'going')
"Hello, Bob! How's it going?"
When you disassemble the function and inspect what’s going on behind the scenes, you’ll see that the f-string in the function
gets transformed into something similar to the following:
>>>
>>> def greet(name, question):
... return "Hello, " + name + "! How's it " + question + "?"
String literals also support the existing format string syntax of the str.format() method. That allows you to solve
the same formatting problems we’ve discussed in the previous two sections:
>>>
>>> f"Hey {name}, there's a {errno:#x} error!"
"Hey Bob, there's a 0xbadc0ffee error!"
Python’s new formatted string literals are similar to JavaScript’s
Template Literals added in ES2015.
I think they’re quite a nice addition to Python, and I’ve already started using them in my day to day (Python 3) work. You can learn
more about formatted string literals in our in-depth Python f-strings tutorial.
#4 Template Strings (Standard Library)
Here's one more tool for string formatting in Python: template strings. It's a simpler and less powerful mechanism, but in some
cases this might be exactly what you're looking for.
Let's take a look at a simple greeting example:
>>>
>>> from string import Template
>>> t = Template('Hey, $name!')
>>> t.substitute(name=name)
'Hey, Bob!'
You see here that we need to import the Template class from Python's built-in string module. Template
strings are not a core language feature but they're supplied by the string module in the standard library.
Another difference is that template strings don't allow format specifiers. So in order to get the previous error string example
to work, you'll need to manually transform the int error number into a hex-string:
>>>
>>> templ_string = 'Hey $name, there is a $error error!'
>>> Template(templ_string).substitute(
... name=name, error=hex(errno))
'Hey Bob, there is a 0xbadc0ffee error!'
That worked great.
So when should you use template strings in your Python programs? In my opinion, the best time to use template strings is when
you're handling formatted strings generated by users of your program. Due to their reduced complexity, template strings are a safer
choice.
That means, if a malicious user can supply a format string, they can potentially leak secret keys and other sensitive information!
Here's a simple proof of concept of how this attack might be used against your code:
>>>
>>> # This is our super secret key:
>>> SECRET = 'this-is-a-secret'
>>> class Error:
... def __init__(self):
... pass
>>> # A malicious user can craft a format string that
>>> # can read data from the global namespace:
>>> user_input = '{error.__init__.__globals__[SECRET]}'
>>> # This allows them to exfiltrate sensitive information,
>>> # like the secret key:
>>> err = Error()
>>> user_input.format(error=err)
'this-is-a-secret'
See how a hypothetical attacker was able to extract our secret string by accessing the __globals__ dictionary from
a malicious format string? Scary, huh? Template strings close this attack vector. This makes them a safer choice if you're handling
format strings generated from user input:
>>>
>>> user_input = '${error.__init__.__globals__[SECRET]}'
>>> Template(user_input).substitute(error=err)
ValueError:
"Invalid placeholder in string: line 1, col 1"
I totally get that having so much choice for how to format your strings in Python can feel very confusing. This is an excellent
cue to bust out this handy flowchart infographic I've put together for you:
Python
String Formatting Rule of Thumb (Image:
Click to Tweet)
This flowchart is based on the rule of thumb that I apply when I'm writing Python:
Perhaps surprisingly, there's more than one way to handle string formatting in Python.
Each method has its individual pros and cons. Your use case will influence which method you should use.
If you're having trouble deciding which string formatting method to use, try our Python String Formatting Rule of Thumb.
Watch Now This tutorial has a related video course created by
the Real Python team. Watch it together with the written tutorial to deepen your understanding:
Python String Formatting Tips & Best Practices
🐍 Python Tricks 💌
Get a short & sweet Python Trick delivered to your
The Last but not LeastTechnology is dominated by
two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt.
Ph.D
FAIR USE NOTICEThis site contains
copyrighted material the use of which has not always been specifically
authorized by the copyright owner. We are making such material available
to advance understanding of computer science, IT technology, economic, scientific, and social
issues. We believe this constitutes a 'fair use' of any such
copyrighted material as provided by section 107 of the US Copyright Law according to which
such material can be distributed without profit exclusively for research and educational purposes.
This is a Spartan WHYFF (We Help You For Free)
site written by people for whom English is not a native language. Grammar and spelling errors should
be expected. The site contain some broken links as it develops like a living tree...
You can use PayPal to to buy a cup of coffee for authors
of this site
Disclaimer:
The statements, views and opinions presented on this web page are those of the author (or
referenced source) and are
not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society.We do not warrant the correctness
of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be
tracked by Google please disable Javascript for this site. This site is perfectly usable without
Javascript.