Explain string format syntax in Python 3

Time:2020-12-1

1、 Old style string formatting

%Operator

Refer to the following example:


>>> name = "Eric"
>>> "Hello, %s." % name
'Hello, Eric.'

When more than one variable needs to be inserted into a string:


>>> name = "Eric"
>>> age = 74
>>> "Hello, %s. You are %s." % (name, age)
'Hello, Eric. You are 74.'

When the number of variables to be replaced increases further, using the% operator to format the string will result in poor code readability


>>> first_name = "Eric"
>>> last_name = "Idle"
>>> age = 74
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> "Hello, %s %s. You are %s. You are a %s. You were a member of %s." % (first_name, last_name, age, profession, affiliation)
'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'

str.format()

str.format () is an improvement on the% mode, which uses the common syntax of function call and can define the__ format__ The () method controls the specific behavior of string formatting.

Basic usage:


>>> name = "Eric"
>>> age = 74
>>> "Hello, {}. You are {}.".format(name, age)
'Hello, Eric. You are 74.'

str.format () is more flexible than the% operator. For example, you can associate variables that are replaced in a string through a numeric index:


>>> name = "Eric"
>>> age = 74
>>> "Hello, {1}. You are {0}.".format(age, name)
'Hello, Eric. You are 74.'

In order to improve the readability of the code, parameter names with specific meanings can also be used in {}:


>>> name = "Eric"
>>> age = 74
>>> "Hello, {name}. You are {age}".format(name=name, age=age)
'Hello, Eric. You are 74'

Data for dictionary structure:


>>> person = {'name': 'Eric', 'age': 74}
>>> "Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
'Hello, Eric. You are 74.'

Or more succinctly:


>>> person = {'name': 'Eric', 'age': 74}
>>> "Hello, {name}. You are {age}.".format(**person)
'Hello, Eric. You are 74.'

The problem is that when there are a lot of variables to replace str.format () mode still makes the code too long:


>>> first_name = "Eric"
>>> last_name = "Idle"
>>> age = 74
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> "Hello, {first_name} {last_name}. You are {age}. \
 You are a {profession}. You were a member of {affiliation}."\
 .format(first_name=first_name, last_name=last_name, age=age, \
 profession=profession, affiliation=affiliation)
'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'

2、 F-string

Basic Usage


>>> name = "Eric"
>>> age = 74
>>> f"Hello, {name}. You are {age}."
'Hello, Eric. You are 74.'

Embedded expression


>>> f"{2 * 37}"
'74'

>>> def to_lowercase(input):
...  return input.lower()
 
>>> name = "Eric Idle"
>>> f"{to_lowercase(name)} is funny"
'eric idle is funny'

>>> f"{name.lower()} is funny"
'eric idle is funny'

An object instance can also be directly embedded in f-string as long as its internal implementation is implemented__ str__ Or__ repr__ method:

class Comedian:
 def __init__(self, first_name, last_name, age):
  self.first_name = first_name
  self.last_name = last_name
  self.age = age

 def __str__(self):
  return f"{self.first_name} {self.last_name} is {self.age}"


new_comedian = Comedian("Eric", "Idle", 74)
print(f"{new_comedian}")
# Eric Idle is 74
Multiline f-string
>>> name = "Eric"
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> message = (
...  f"Hi {name}. "
...  f"You are a {profession}. "
...  f"You were in {affiliation}."
... )
>>> message
'Hi Eric. You are a comedian. You were in Monty Python.'

summary

The above is the string format syntax of Python 3 introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message, and the editor will reply you in time. Thank you very much for your support to the developeppaer website!
If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!

Recommended Today

Interviewer: young man, what do you think of the principle of distributed system

1 Concept 1.1 model 1.2 copies 1.3 indicators for measuring distributed systems 2. Principle of distributed system 2.1 data distribution 2.2 basic copy agreement 2.3 lease mechanism 2.4 quorum mechanism 2.5 log technology 2.6 two phase submission protocol 2.7 MVCC 2.8 Paxos protocol 2.9 CAP 1 Concept 1.1 model node In a specific project, a […]