Hướng dẫn python f-string escape quotes - dấu ngoặc kép python f-string Escape

Thật đáng tiếc khi định dạng tích hợp không cho phép điều đó. Một phần mở rộng cú pháp rõ ràng sẽ là cho phép các khóa được trích dẫn, nếu cần thiết. Chuỗi định dạng của bạn sau đó sẽ như thế này:

Show

Nội phân chính

  • Chuỗi của trường cũ ở trường học ở Python
  • Tùy chọn số 1: %-Formatting
  • Tùy chọn #2: str.format ()
  • F-Strings: Một cách mới và được cải tiến để định dạng chuỗi trong Python
  • Cú pháp đơn giản
  • Biểu thức tùy ý
  • Multiline F-String
  • Python F-Strings: Các chi tiết phiền phức
  • Dấu ngoặc kép
  • Từ điển
  • Dấu gạch chéo ngược
  • Đi ra và định dạng!
  • Đọc thêm

format('{"with:colon"} and {hello}'

May mắn thay, nó dường như dễ dàng mở rộng định dạng để cung cấp cú pháp này, đây là triển khai POC:

class QuotableFormatter(string.Formatter):
    def __init__(self):
        self.super = super(QuotableFormatter, self)
        self.super.__init__()
        self.quotes = {}

    def parse(self, format_string):
        fs = ''
        for p in re.findall(r'(?:".+?")|(?:[^"]+)', format_string):
            if p[0] == '"':
                key = '_q_' + str(len(self.quotes))
                self.quotes[key] = p[1:-1]
                fs += key
            else:
                fs += p
        return self.super.parse(fs)

    def get_field(self, field_name, args, kwargs):
        if field_name.startswith('_q_'):
            field_name = self.quotes[field_name]
        return self.super.get_field(field_name, args, kwargs)

Usage:

d = {'hello': 'world', 'with:colon': 'moo', "weird!r:~^20": 'hi'}
print QuotableFormatter().format('{"with:colon":*>20} and {hello} and {"weird!r:~^20"}', **d)
# *****************moo and world and hi

Kể từ Python 3.6, dây F là một cách mới tuyệt vời để định dạng chuỗi. Họ không chỉ dễ đọc hơn, súc tích hơn và ít bị lỗi hơn so với các cách định dạng khác, mà chúng còn nhanh hơn!

Đến cuối bài viết này, bạn sẽ tìm hiểu cách thức và lý do bắt đầu sử dụng F-Strings ngay hôm nay.

Nhưng trước tiên, ở đây, cuộc sống như thế nào trước F-String, trở lại khi bạn phải đi bộ đến trường lên dốc cả hai cách trong tuyết.

Chuỗi của trường cũ ở trường học ở Python

Tùy chọn số 1: %-Formatting

Tùy chọn số 1: %-Formatting

Tùy chọn #2: str.format ()

F-Strings: Một cách mới và được cải tiến để định dạng chuỗi trong Python

Cú pháp đơn giản

Biểu thức tùy ý

Multiline F-String

Python F-Strings: Các chi tiết phiền phức

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

Dấu ngoặc kép

Python F-Strings: Các chi tiết phiền phức

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

Dấu ngoặc kép

Từ điển

Python F-Strings: Các chi tiết phiền phức

>>> 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.'

Dấu ngoặc kép

Tùy chọn #2: str.format ()

F-Strings: Một cách mới và được cải tiến để định dạng chuỗi trong Python

Cú pháp đơn giản

Biểu thức tùy ý

Multiline F-String

Python F-Strings: Các chi tiết phiền phức

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

Dấu ngoặc kép

Python F-Strings: Các chi tiết phiền phức

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

Dấu ngoặc kép

Python F-Strings: Các chi tiết phiền phức

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

Dấu ngoặc kép

Python F-Strings: Các chi tiết phiền phức

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

Dấu ngoặc kép

Từ điển

Dấu gạch chéo ngược

Python F-Strings: Các chi tiết phiền phức

class QuotableFormatter(string.Formatter):
    def __init__(self):
        self.super = super(QuotableFormatter, self)
        self.super.__init__()
        self.quotes = {}

    def parse(self, format_string):
        fs = ''
        for p in re.findall(r'(?:".+?")|(?:[^"]+)', format_string):
            if p[0] == '"':
                key = '_q_' + str(len(self.quotes))
                self.quotes[key] = p[1:-1]
                fs += key
            else:
                fs += p
        return self.super.parse(fs)

    def get_field(self, field_name, args, kwargs):
        if field_name.startswith('_q_'):
            field_name = self.quotes[field_name]
        return self.super.get_field(field_name, args, kwargs)
0

Dấu ngoặc kép

Từ điển

Dấu gạch chéo ngược

Đi ra và định dạng!

Dưới đây là một số cách mà F-String có thể làm cho cuộc sống của bạn dễ dàng hơn.

Cú pháp đơn giản

Cú pháp tương tự như cái bạn đã sử dụng với

>>> name = "Eric"
>>> "Hello, %s." % name
'Hello, Eric.'
7 nhưng ít dài dòng hơn. Nhìn vào cách dễ đọc này:

>>>

class QuotableFormatter(string.Formatter):
    def __init__(self):
        self.super = super(QuotableFormatter, self)
        self.super.__init__()
        self.quotes = {}

    def parse(self, format_string):
        fs = ''
        for p in re.findall(r'(?:".+?")|(?:[^"]+)', format_string):
            if p[0] == '"':
                key = '_q_' + str(len(self.quotes))
                self.quotes[key] = p[1:-1]
                fs += key
            else:
                fs += p
        return self.super.parse(fs)

    def get_field(self, field_name, args, kwargs):
        if field_name.startswith('_q_'):
            field_name = self.quotes[field_name]
        return self.super.get_field(field_name, args, kwargs)
1

Nó cũng sẽ có hiệu lực khi sử dụng một chữ cái viết hoa

>>> 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.'
2:

>>>

class QuotableFormatter(string.Formatter):
    def __init__(self):
        self.super = super(QuotableFormatter, self)
        self.super.__init__()
        self.quotes = {}

    def parse(self, format_string):
        fs = ''
        for p in re.findall(r'(?:".+?")|(?:[^"]+)', format_string):
            if p[0] == '"':
                key = '_q_' + str(len(self.quotes))
                self.quotes[key] = p[1:-1]
                fs += key
            else:
                fs += p
        return self.super.parse(fs)

    def get_field(self, field_name, args, kwargs):
        if field_name.startswith('_q_'):
            field_name = self.quotes[field_name]
        return self.super.get_field(field_name, args, kwargs)
2

Nó cũng sẽ có hiệu lực khi sử dụng một chữ cái viết hoa

>>> 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.'
2:

Bạn có yêu F-String chưa? Tôi hy vọng rằng, vào cuối bài viết này, bạn sẽ trả lời >>> 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.' 3.

Biểu thức tùy ý

Bởi vì các chuỗi F được đánh giá trong thời gian chạy, bạn có thể đặt bất kỳ và tất cả các biểu thức python hợp lệ trong chúng. Điều này cho phép bạn làm một số điều tiện lợi.

Bạn có thể làm một cái gì đó khá đơn giản, như thế này:

>>>

class QuotableFormatter(string.Formatter):
    def __init__(self):
        self.super = super(QuotableFormatter, self)
        self.super.__init__()
        self.quotes = {}

    def parse(self, format_string):
        fs = ''
        for p in re.findall(r'(?:".+?")|(?:[^"]+)', format_string):
            if p[0] == '"':
                key = '_q_' + str(len(self.quotes))
                self.quotes[key] = p[1:-1]
                fs += key
            else:
                fs += p
        return self.super.parse(fs)

    def get_field(self, field_name, args, kwargs):
        if field_name.startswith('_q_'):
            field_name = self.quotes[field_name]
        return self.super.get_field(field_name, args, kwargs)
3

Nó cũng sẽ có hiệu lực khi sử dụng một chữ cái viết hoa

>>> 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.'
2:

>>>

class QuotableFormatter(string.Formatter):
    def __init__(self):
        self.super = super(QuotableFormatter, self)
        self.super.__init__()
        self.quotes = {}

    def parse(self, format_string):
        fs = ''
        for p in re.findall(r'(?:".+?")|(?:[^"]+)', format_string):
            if p[0] == '"':
                key = '_q_' + str(len(self.quotes))
                self.quotes[key] = p[1:-1]
                fs += key
            else:
                fs += p
        return self.super.parse(fs)

    def get_field(self, field_name, args, kwargs):
        if field_name.startswith('_q_'):
            field_name = self.quotes[field_name]
        return self.super.get_field(field_name, args, kwargs)
4

Nó cũng sẽ có hiệu lực khi sử dụng một chữ cái viết hoa

>>> 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.'
2:

class QuotableFormatter(string.Formatter):
    def __init__(self):
        self.super = super(QuotableFormatter, self)
        self.super.__init__()
        self.quotes = {}

    def parse(self, format_string):
        fs = ''
        for p in re.findall(r'(?:".+?")|(?:[^"]+)', format_string):
            if p[0] == '"':
                key = '_q_' + str(len(self.quotes))
                self.quotes[key] = p[1:-1]
                fs += key
            else:
                fs += p
        return self.super.parse(fs)

    def get_field(self, field_name, args, kwargs):
        if field_name.startswith('_q_'):
            field_name = self.quotes[field_name]
        return self.super.get_field(field_name, args, kwargs)
5

Bạn có yêu F-String chưa? Tôi hy vọng rằng, vào cuối bài viết này, bạn sẽ trả lời

>>> 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.'
3.

>>>

class QuotableFormatter(string.Formatter):
    def __init__(self):
        self.super = super(QuotableFormatter, self)
        self.super.__init__()
        self.quotes = {}

    def parse(self, format_string):
        fs = ''
        for p in re.findall(r'(?:".+?")|(?:[^"]+)', format_string):
            if p[0] == '"':
                key = '_q_' + str(len(self.quotes))
                self.quotes[key] = p[1:-1]
                fs += key
            else:
                fs += p
        return self.super.parse(fs)

    def get_field(self, field_name, args, kwargs):
        if field_name.startswith('_q_'):
            field_name = self.quotes[field_name]
        return self.super.get_field(field_name, args, kwargs)
6

Nó cũng sẽ có hiệu lực khi sử dụng một chữ cái viết hoa

>>> 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.'
2:

Bạn có yêu F-String chưa? Tôi hy vọng rằng, vào cuối bài viết này, bạn sẽ trả lời

>>> 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.'
3.

Biểu thức tùy ý

>>>

class QuotableFormatter(string.Formatter):
    def __init__(self):
        self.super = super(QuotableFormatter, self)
        self.super.__init__()
        self.quotes = {}

    def parse(self, format_string):
        fs = ''
        for p in re.findall(r'(?:".+?")|(?:[^"]+)', format_string):
            if p[0] == '"':
                key = '_q_' + str(len(self.quotes))
                self.quotes[key] = p[1:-1]
                fs += key
            else:
                fs += p
        return self.super.parse(fs)

    def get_field(self, field_name, args, kwargs):
        if field_name.startswith('_q_'):
            field_name = self.quotes[field_name]
        return self.super.get_field(field_name, args, kwargs)
7

Nó cũng sẽ có hiệu lực khi sử dụng một chữ cái viết hoa

>>> 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.'
2:

Bạn có yêu F-String chưa? Tôi hy vọng rằng, vào cuối bài viết này, bạn sẽ trả lời >>> 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.' 3.

Biểu thức tùy ý

>>>

class QuotableFormatter(string.Formatter):
    def __init__(self):
        self.super = super(QuotableFormatter, self)
        self.super.__init__()
        self.quotes = {}

    def parse(self, format_string):
        fs = ''
        for p in re.findall(r'(?:".+?")|(?:[^"]+)', format_string):
            if p[0] == '"':
                key = '_q_' + str(len(self.quotes))
                self.quotes[key] = p[1:-1]
                fs += key
            else:
                fs += p
        return self.super.parse(fs)

    def get_field(self, field_name, args, kwargs):
        if field_name.startswith('_q_'):
            field_name = self.quotes[field_name]
        return self.super.get_field(field_name, args, kwargs)
8

Nó cũng sẽ có hiệu lực khi sử dụng một chữ cái viết hoa

>>> 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.'
2:

>>>

class QuotableFormatter(string.Formatter):
    def __init__(self):
        self.super = super(QuotableFormatter, self)
        self.super.__init__()
        self.quotes = {}

    def parse(self, format_string):
        fs = ''
        for p in re.findall(r'(?:".+?")|(?:[^"]+)', format_string):
            if p[0] == '"':
                key = '_q_' + str(len(self.quotes))
                self.quotes[key] = p[1:-1]
                fs += key
            else:
                fs += p
        return self.super.parse(fs)

    def get_field(self, field_name, args, kwargs):
        if field_name.startswith('_q_'):
            field_name = self.quotes[field_name]
        return self.super.get_field(field_name, args, kwargs)
9

Nó cũng sẽ có hiệu lực khi sử dụng một chữ cái viết hoa

>>> 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.'
2:

Bạn có yêu F-String chưa? Tôi hy vọng rằng, vào cuối bài viết này, bạn sẽ trả lời

>>> 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.'
3.

>>>

d = {'hello': 'world', 'with:colon': 'moo', "weird!r:~^20": 'hi'}
print QuotableFormatter().format('{"with:colon":*>20} and {hello} and {"weird!r:~^20"}', **d)
# *****************moo and world and hi
0

Nó cũng sẽ có hiệu lực khi sử dụng một chữ cái viết hoa

>>> 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.'
2:

>>>

d = {'hello': 'world', 'with:colon': 'moo', "weird!r:~^20": 'hi'}
print QuotableFormatter().format('{"with:colon":*>20} and {hello} and {"weird!r:~^20"}', **d)
# *****************moo and world and hi
1

Nó cũng sẽ có hiệu lực khi sử dụng một chữ cái viết hoa

>>> 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.'
2:

Bạn có yêu F-String chưa? Tôi hy vọng rằng, vào cuối bài viết này, bạn sẽ trả lời >>> 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.' 3.

Biểu thức tùy ý

Bởi vì các chuỗi F được đánh giá trong thời gian chạy, bạn có thể đặt bất kỳ và tất cả các biểu thức python hợp lệ trong chúng. Điều này cho phép bạn làm một số điều tiện lợi.

Bạn có thể làm một cái gì đó khá đơn giản, như thế này:

Nhưng bạn cũng có thể gọi các chức năng. Đây là một ví dụ:

Bạn cũng có tùy chọn gọi trực tiếp một phương thức:

>>>

d = {'hello': 'world', 'with:colon': 'moo', "weird!r:~^20": 'hi'}
print QuotableFormatter().format('{"with:colon":*>20} and {hello} and {"weird!r:~^20"}', **d)
# *****************moo and world and hi
2

>>>

d = {'hello': 'world', 'with:colon': 'moo', "weird!r:~^20": 'hi'}
print QuotableFormatter().format('{"with:colon":*>20} and {hello} and {"weird!r:~^20"}', **d)
# *****************moo and world and hi
3

>>>

d = {'hello': 'world', 'with:colon': 'moo', "weird!r:~^20": 'hi'}
print QuotableFormatter().format('{"with:colon":*>20} and {hello} and {"weird!r:~^20"}', **d)
# *****************moo and world and hi
4

Bạn thậm chí có thể sử dụng các đối tượng được tạo từ các lớp có chuỗi F. Hãy tưởng tượng bạn đã có lớp học sau:

Bạn có thể làm điều này:

Các phương thức >>> 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.' 4 và >>> 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.' 5 đối phó với cách các đối tượng được trình bày dưới dạng chuỗi, vì vậy bạn sẽ cần đảm bảo rằng bạn bao gồm ít nhất một trong các phương thức đó trong định nghĩa lớp của bạn. Nếu bạn phải chọn một, hãy đi với >>> 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.' 5 vì nó có thể được sử dụng thay cho >>> 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.' 4.

Chuỗi được trả về bởi

>>> 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.'
4 là biểu diễn chuỗi không chính thức của một đối tượng và có thể đọc được. Chuỗi được trả về bởi
>>> 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.'
5 là đại diện chính thức và nên không rõ ràng. Gọi
>>> "Hello, {}. You are {}.".format(name, age)
'Hello, Eric. You are 74.'
0 và
>>> "Hello, {}. You are {}.".format(name, age)
'Hello, Eric. You are 74.'
1 tốt hơn là sử dụng trực tiếp
>>> 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.'
4 và
>>> 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.'
5.

Theo mặc định, các chuỗi F sẽ sử dụng >>> 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.' 4, nhưng bạn có thể đảm bảo rằng họ sử dụng >>> 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.' 5 nếu bạn bao gồm cờ chuyển đổi >>> "Hello, {}. You are {}.".format(name, age) 'Hello, Eric. You are 74.' 6:

Nếu bạn muốn đọc một số cuộc trò chuyện dẫn đến các chuỗi F hỗ trợ các biểu thức python đầy đủ, bạn có thể làm như vậy ở đây.

Multiline F-String

>>>

d = {'hello': 'world', 'with:colon': 'moo', "weird!r:~^20": 'hi'}
print QuotableFormatter().format('{"with:colon":*>20} and {hello} and {"weird!r:~^20"}', **d)
# *****************moo and world and hi
5

Bạn có thể có chuỗi đa dòng:

>>>

d = {'hello': 'world', 'with:colon': 'moo', "weird!r:~^20": 'hi'}
print QuotableFormatter().format('{"with:colon":*>20} and {hello} and {"weird!r:~^20"}', **d)
# *****************moo and world and hi
6

Nhưng hãy nhớ rằng bạn cần đặt một

>>> name = "Eric"
>>> age = 74
>>> "Hello, %s. You are %s." % (name, age)
'Hello Eric. You are 74.'
9 trước mỗi dòng của một chuỗi đa dòng. Mã sau đây đã giành được công việc:

>>>

d = {'hello': 'world', 'with:colon': 'moo', "weird!r:~^20": 'hi'}
print QuotableFormatter().format('{"with:colon":*>20} and {hello} and {"weird!r:~^20"}', **d)
# *****************moo and world and hi
7

>>>

d = {'hello': 'world', 'with:colon': 'moo', "weird!r:~^20": 'hi'}
print QuotableFormatter().format('{"with:colon":*>20} and {hello} and {"weird!r:~^20"}', **d)
# *****************moo and world and hi
8

Nếu bạn không đặt một

>>> name = "Eric"
>>> age = 74
>>> "Hello, %s. You are %s." % (name, age)
'Hello Eric. You are 74.'
9 trước mỗi dòng riêng lẻ, thì bạn sẽ có các chuỗi thường xuyên, cũ, trong vườn và không sáng bóng, mới, ưa thích.

>>>

d = {'hello': 'world', 'with:colon': 'moo', "weird!r:~^20": 'hi'}
print QuotableFormatter().format('{"with:colon":*>20} and {hello} and {"weird!r:~^20"}', **d)
# *****************moo and world and hi
9

Nếu bạn muốn lan truyền các chuỗi trên nhiều dòng, bạn cũng có tùy chọn thoát khỏi sự trở lại với >>> "Hello, {}. You are {}.".format(name, age) 'Hello, Eric. You are 74.' 9:

Nhưng đây là những gì sẽ xảy ra nếu bạn sử dụng

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

Đọc về hướng dẫn thụt vào trong PEP 8.

>>>

Tốc độ, vận tốc

>>> name = "Eric"
>>> age = 74
>>> "Hello, %s. You are %s." % (name, age)
'Hello Eric. You are 74.'
9 trong F-String cũng có thể đứng cho Fast Fast.

>>>

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

Nếu bạn sử dụng cùng một loại dấu ngoặc kép xung quanh các khóa từ điển như bạn làm ở bên ngoài chuỗi F, thì dấu ngoặc kép ở đầu khóa từ điển đầu tiên sẽ được hiểu là kết thúc của chuỗi.

Niềng răng

Để làm cho nẹp xuất hiện trong chuỗi của bạn, bạn phải sử dụng niềng răng đôi:

>>>

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

Lưu ý rằng sử dụng niềng răng ba sẽ dẫn đến việc chỉ có niềng răng đơn trong chuỗi của bạn:

>>>

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

Tuy nhiên, bạn có thể nhận được nhiều niềng răng hơn để hiển thị nếu bạn sử dụng nhiều hơn ba niềng răng:

>>>

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

Dấu gạch chéo ngược

Như bạn đã thấy trước đó, bạn có thể sử dụng dấu gạch chéo ngược trong phần chuỗi của chuỗi F. Tuy nhiên, bạn có thể sử dụng các dấu gạch chéo ngược để thoát khỏi phần biểu thức của chuỗi F:

>>>

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

Bạn có thể làm việc xung quanh điều này bằng cách đánh giá biểu thức trước và sử dụng kết quả trong chuỗi F:

>>>

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

Đi ra và định dạng!

Bạn vẫn có thể sử dụng các cách định dạng các chuỗi định dạng cũ hơn, nhưng với các chuỗi F, giờ đây bạn có một cách ngắn gọn, dễ đọc hơn và thuận tiện hơn, vừa nhanh hơn và ít bị lỗi hơn. Đơn giản hóa cuộc sống của bạn bằng cách sử dụng F-Strings là một lý do tuyệt vời để bắt đầu sử dụng Python 3.6 nếu bạn đã thực hiện chuyển đổi. (Nếu bạn vẫn đang sử dụng Python 2, đừng quên rằng năm 2020 sẽ sớm ở đây!)

Theo Zen of Python, khi bạn cần quyết định cách làm một cái gì đó, thì ở đây, ở đây sẽ là một cách và tốt nhất là chỉ có một cách để làm điều đó. Mặc dù các chuỗi F không phải là cách duy nhất có thể để bạn định dạng chuỗi, nhưng chúng ở một vị trí tuyệt vời để trở thành một cách rõ ràng để hoàn thành công việc.

Đọc thêm

Nếu bạn muốn đọc một cuộc thảo luận mở rộng về nội suy chuỗi, hãy xem PEP 502. Ngoài ra, bản nháp PEP 536 có thêm một số suy nghĩ về tương lai của F-String.

Để có thêm niềm vui với chuỗi, hãy xem các bài viết sau:

  • Chuỗi Python định dạng các thực tiễn tốt nhất của Dan Bader
  • Giới thiệu thực tế về việc quét web trong Python của Colin Okeefe

Happy Pythoning!