How do you format text in python?
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 Show
Remember the Zen of Python and how there should be “one obvious way to do something in Python”? You might scratch your head when you find out that there are four major ways to do string formatting in Python. In this tutorial, you’ll learn the four main approaches to string formatting in Python, as well as their strengths and weaknesses. You’ll also get a simple rule of thumb for how to pick the best general purpose string formatting approach in your own programs. Let’s jump right in, as we’ve got a lot to cover. In order to have a simple toy example for experimentation, let’s assume you’ve got the following variables (or constants, really) to work with: >>>
Based on these variables, you’d like to generate an output string containing a simple error message: >>>
That error could really spoil a dev’s Monday morning… But we’re here to discuss string formatting. So let’s get to work. #1 “Old Style” String Formatting (% Operator)Strings
in Python have a unique built-in operation that can be accessed with the >>>
I’m using the There are other format specifiers available that let you control the output format. For example, it’s possible to convert numbers to hexadecimal notation or add whitespace padding to generate nicely formatted tables and reports. (See Python Docs: “printf-style String Formatting”.) Here, you can use the
>>>
The “old style” string formatting syntax changes slightly if you want to make multiple substitutions in a single string. Because the >>>
It’s also possible to refer to variable substitutions by name in your format string, if you pass a mapping to the >>>
This makes your format strings easier to maintain and easier to modify in the future. You don’t have to worry about making sure the order you’re passing in the values matches up with the order in which the values are referenced in the format string. Of course, the downside is that this technique requires a little more typing. I’m sure you’ve been wondering why this #2 “New Style” String Formatting (str.format)Python 3 introduced a new way to do string formatting that was also later back-ported to Python 2.7. This “new style” string formatting gets rid of the You can use >>>
Or, you can refer to your variable substitutions by name and use them in any order you want. This is quite a powerful feature as it allows
for re-arranging the order of display without changing the arguments passed to >>>
This also shows that the syntax to format an In Python 3, this “new style” string formatting is to be preferred over Still, the official Python 3 documentation doesn’t exactly recommend “old style” formatting or speak too fondly of it:
This is why I’d personally try to stick with #3 String Interpolation / f-Strings (Python 3.6+)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: >>>
As you can see, this prefixes the string constant with the letter “ >>>
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 >>>
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: >>>
The real implementation is slightly faster than that because it uses the >>>
String literals also support the existing format string syntax of the >>>
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: >>>
You see here that we need to import the 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 >>>
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. The more complex formatting mini-languages of the other string formatting techniques might introduce security vulnerabilities to your programs. For example, it’s possible for format strings to access arbitrary variables in your program. 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: >>>
See how a hypothetical attacker was able to extract our secret string by accessing the >>>
Which String Formatting Method Should You Use?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: Key Takeaways
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 How do you write format in Python?The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.
What is str format () in Python?String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text.
What is %s and %D in Python?%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values.
How do you use %s in Python?The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. The following Python code illustrates the way of performing string formatting.
|