Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are formatted string literals in Python 3.6?

One of the features of Python 3.6 are formatted strings.

This SO question(String with 'f' prefix in python-3.6) is asking about the internals of formatted string literals, but I don't understand the exact use case of formatted string literals. In which situations should I use this feature? Isn't explicit better than implicit?

like image 812
Günther Jena Avatar asked Aug 22 '16 14:08

Günther Jena


People also ask

What is formatted string literal in Python?

Formatted string literals (also called f-strings for short) let you include the value of Python expressions inside a string by prefixing the string with f or F and writing expressions as {expression} .

What was introduced in Python 3.6 that changed string formatting?

Python 3.6 introduced a new way to format strings: f-Strings. It is faster than other string formatting methods in Python, and they allow us to evaluate Python expressions inside a string.

Does Python 3.5 have F-strings?

Well, f-strings are only available since Python 3.6.

What does formatted string mean?

String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text.


2 Answers

Simple is better than complex.

So here we have formatted string. It gives the simplicity to the string formatting, while keeping the code explicit (comprared to other string formatting mechanisms).

title = 'Mr.'
name = 'Tom'
count = 3

# This is explicit but complex
print('Hello {title} {name}! You have {count} messages.'.format(title=title, name=name, count=count))

# This is simple but implicit
print('Hello %s %s! You have %d messages.' % (title, name, count))

# This is both explicit and simple. PERFECT!
print(f'Hello {title} {name}! You have {count} messages.')

It is designed to replace str.format for simple string formatting.

like image 129
xmcp Avatar answered Sep 24 '22 12:09

xmcp


Pro: F-literal has better performance.(See below)

Con: F-literal is a new 3.6 feature.

In [1]: title = 'Mr.'
   ...: name = 'Tom'
   ...: count = 3
   ...: 
   ...: 

In [2]: %timeit 'Hello {title} {name}! You have {count} messages.'.format(title=title, name=name, count=count)
330 ns ± 1.08 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [3]: %timeit 'Hello %s %s! You have %d messages.'%(title, name, count)
417 ns ± 1.76 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [4]: %timeit f'Hello {title} {name}! You have {count} messages.'
13 ns ± 0.0163 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
like image 25
zhengcao Avatar answered Sep 21 '22 12:09

zhengcao