In Python, it is customary to format strings using %s or format. In Python 3.6, a new option, f-string, was introduced.
Use the compare
Let’s start by looking at a comparison of the use of formatted strings that already exist in Python.
# %s
username = 'tom'
action = 'payment'
message = 'User %s has logged in and did an action %s.' % (username, action)
print(message)
# format
username = 'tom'
action = 'payment'
message = 'User {} has logged in and did an action {}.'.format(username, action)
print(message)
# f-string
username = 'tom'
action = 'payment'
message = f'User {user} has logged in and did an action {action}.'
print(message)
f"{2 * 3}"
# 6
comedian = {'name': 'Tom'.'age': 20}
f"The comedian is {comedian['name']}, aged {comedian['age']}."
# 'The comedian is Tom, aged 20.'
Copy the code
F-strings directly inserts variables into placeholders is much more convenient and understandable than the common string format %s or format methods.
Convenient converter
F-string is currently the best concatenated string form, with more power, let’s look at the structure of f-string.
f '
{
}
... '
Copy the code
The ‘! S ‘calls STR () on the expression, ‘! R ‘calls repr() on the expression, ‘! A ‘calls ASCII () on the expression.
- By default, f-string will use STR (), but if the conversion flag is included! R, you can use repr()
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f'str - name: {self.name}, age: {self.age}'
def __repr__(self):
return f'repr - name: {self.name}, age: {self.age}'
p = Person('tom', 20)
f'{p}'
# str - name: tom, age: 20
f'{p! r}'
# repr - name: tom, age: 20
Copy the code
- Switch flags! a
a = 'a string'
f'{a! a}'
# "'a string'"
Copy the code
- Is equivalent to
f'{repr(a)}'
# "'a string'"
Copy the code
performance
In addition to providing powerful formatting capabilities, f-string is the most high-performance implementation of the three formatting methods.
>>> import timeit
>>> timeit.timeit("""name = "Eric"... age = 74 ... '%s is %s.' % (name, age)""", number = 10000)
0.003324444866599663
>>> timeit.timeit("""name = "Eric"... age = 74 ... '{} is {}.'.format(name, age)""", number = 10000) 0.004242089427570761 >>> timeit. Timeit ("""name = "Eric"... age = 74 ... f'{name} is {age}.'""", number = 10000)
0.0024820892040722242
Copy the code
For Python 3.6+ users, use f-string instead of your format function for more power and performance.
More Python tutorials will continue to be updated!