5.4. Formatting Strings

Strings appear in almost every computer program, no matter the language. This data type is common, so it’s no surprise there are many approaches to manipulating and formatting strings. This section highlights a couple of best practices. ## Use Raw Strings If Your String Has Many Backslashes Escape characters allow you to insert text into string literals that would other­ wise be impossible to include. For example, you need the  in ‘Zophie's chair’ so Python interprets the second quote as part of the string, not the symbol marking the end of the string. Because the backslash has this spe- cial escape meaning, if you want to put an actual backslash character in your string, you must enter it as \ .

Raw strings are string literals that have an r prefix, and they don’t treat the backslash characters as escape characters. Instead, they just put the backslashes into the string. For example, this string of a Windows file path requires several escaped backslashes, which isn’t very pythonic:

>>> # Unpythonic Example
>>> print('The file is in C:\\Users\\Al\\Desktop\\Info\\Archive\\Spam')
The file is in C:UsersAlDesktopInfoArchiveSpam

This raw string (notice the r prefix) produces the same string value while being more readable:

>>> # Pythonic Example
>>> print(r'The file is in C:\Users\Al\Desktop\Info\Archive\Spam')
The file is in C:UsersAlDesktopInfoArchiveSpam

Raw strings aren’t a different kind of string data type; they’re just a convenient way to type string literals that contain several backslash charac- ters. We often use raw strings to type the strings for regular expressions or Windows file paths, which often have several backslash characters in them that would be a pain to escape individually with \\ .

5.4.1. Format Strings with F-Strings

String formatting, or string interpolation, is the process of creating strings that include other strings and has had a long history in Python. Originally, the + operator could concatenate strings together, but this resulted in code with many quotes and pluses: ‘Hello,’ + name + ‘. Today is’ + day + ’ and it is ’ + weather + ‘.’ . The %s conversion specifier made the syntax a bit easier: ‘Hello, %s. Today is %s and it is %s.’ % (name, day, weather) . Both tech- niques will insert the strings in the name , day , and weather variables into the string literals to evaluate to a new string value, like this: ‘Hello, Al. Today is Sunday and it is sunny.’ .

The format() string method adds the Format Specification Mini-Language (https://docs.python.org/3/library/string.html#formatspec), which involves using {} brace pairs in a way similar to the %s conversion specifier. However, the method is somewhat convoluted and can produce unreadable code, so I dis- courage its use.

But as of Python 3.6, f-strings (short for format strings) offer a more con- venient way to create strings that include other strings. Just like how raw strings are prefixed with an r before the first quote, f-strings are prefixed with an f . You can include variable names in between braces in the f-string to insert the strings stored in those variables:

>>> name, day, weather = 'Al', 'Sunday', 'sunny'
>>>
>>> f'Hello, {name}. Today is {day} and it is {weather}.'
'Hello, Al. Today is Sunday and it is sunny.'

The braces can contain entire expressions as well:

>>> width, length = 10, 12
>>>
>>> f'A {width} by {length} room has an area of {width * length}.'
'A 10 by 12 room has an area of 120.'

If you need to use a literal brace inside an f-string, you can escape it with an additional brace:

>>> spam = 42
>>>
>>> f'This prints the value in spam: {spam}'
'This prints the value in spam: 42'
>>> f'This prints literal curly braces: {{spam}}'
'This prints literal curly braces: {spam}'

Because you can put variable names and expressions inline inside the string, your code becomes more readable than using the old ways of string formatting.

All of these different ways to format strings go against the Zen of Python aphorism that there should be one—and preferably only one—obvious way to do something. But f-strings are an improvement to the language (in my opinion), and as the other guideline states, practicality beats purity. If you’re writing code for Python 3.6 or later only, use f-strings. If you’re writing code that might be run by earlier Python versions, stick to the format() string method or %s conversion specifiers.