Hướng dẫn python string format ignore keyerror - định dạng chuỗi python bỏ qua keyerror

Giải pháp chính thức [tài liệu Python 3] cho các chuỗi trong ánh xạ định dạng là phân lớp lớp dict và xác định phương pháp ma thuật __missing__[]. Phương pháp này được gọi bất cứ khi nào thiếu khóa và thay vào đó, những gì nó được sử dụng cho định dạng chuỗi:

class format_dict[dict]:
    def __missing__[self, key]:
        return "..."

d = format_dict[{"foo": "name"}]

print["My %[foo]s is %[bar]s" % d] # "My name is ..."

print["My {foo} is {bar}".format[**d]] # "My name is ..."

Chỉnh sửa: Bản in thứ hai [] hoạt động trong Python 3.5.3, nhưng nó không có trong ví dụ: 3.7.2: KeyError: 'bar' được nâng lên và tôi không thể tìm cách bắt nó. the second print[] works in Python 3.5.3, but it does not in e.g. 3.7.2: KeyError: 'bar' is raised and I couldn't find a way to catch it.

Sau một số thí nghiệm, tôi đã tìm thấy một sự khác biệt trong hành vi của Python. Trong v3.5.3, các cuộc gọi là __getitem__[self, "foo"] thành công và

from collections import defaultdict
    
d = defaultdict[lambda: "..."]
d.update[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is ..."
0 không thể tìm thấy khóa
from collections import defaultdict
    
d = defaultdict[lambda: "..."]
d.update[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is ..."
1, do đó, nó gọi
from collections import defaultdict
    
d = defaultdict[lambda: "..."]
d.update[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is ..."
2 để xử lý phím bị thiếu mà không cần ném KeyError. Trong v3.7.2,
from collections import defaultdict
    
d = defaultdict[lambda: "..."]
d.update[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is ..."
3 được gọi là nội bộ. Phương pháp
from collections import defaultdict
    
d = defaultdict[lambda: "..."]
d.update[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is ..."
4 tích hợp được sử dụng để trả về một trình lặp qua các phím, mang lại "foo",
from collections import defaultdict
    
d = defaultdict[lambda: "..."]
d.update[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is ..."
5 thành công, sau đó trình lặp bị cạn kiệt. Đối với
from collections import defaultdict
    
d = defaultdict[lambda: "..."]
d.update[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is ..."
6 từ chuỗi định dạng không có khóa
from collections import defaultdict
    
d = defaultdict[lambda: "..."]
d.update[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is ..."
1.
from collections import defaultdict
    
d = defaultdict[lambda: "..."]
d.update[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is ..."
8 và do đó
from collections import defaultdict
    
d = defaultdict[lambda: "..."]
d.update[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is ..."
9 không được gọi để xử lý tình huống. Thay vào đó, KeyError bị ném. Tôi không biết làm thế nào người ta có thể bắt được nó, nếu có.

Trong Python 3.2+, bạn nên sử dụng

class Default[dict]:
    def __missing__[self, key]: 
        return key.join["{}"]
    
d = Default[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is {bar}"
0 thay thế [cũng xem Trình theo dõi lỗi Python - Số phát hành 6081]: [also see Python Bug Tracker - Issue 6081]:

from collections import defaultdict
    
d = defaultdict[lambda: "..."]
d.update[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is ..."

Nếu bạn muốn giữ chỗ giữ chỗ, bạn có thể làm:keep the placeholders, you can do:

class Default[dict]:
    def __missing__[self, key]: 
        return key.join["{}"]
    
d = Default[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is {bar}"

Như bạn có thể thấy,

class Default[dict]:
    def __missing__[self, key]: 
        return key.join["{}"]
    
d = Default[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is {bar}"
0 gọi __missing__[].

Sau đây dường như là giải pháp tương thích nhất vì nó cũng hoạt động trong các phiên bản Python cũ hơn bao gồm 2.x [tôi đã thử nghiệm v2.7.15]:

class Default[dict]:
    def __missing__[self, key]:
        return key.join["{}"]

d = Default[{"foo": "name"}]

import string
print[string.Formatter[].vformat["My {foo} is {bar}", [], d]] # "My name is {bar}"

Để giữ các khoản giữ chỗ là-bao gồm cả thông số kỹ thuật định dạng [ví dụ:

class Default[dict]:
    def __missing__[self, key]: 
        return key.join["{}"]
    
d = Default[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is {bar}"
3], định dạng cần phải được phân nhóm:including the format spec [e.g.
class Default[dict]:
    def __missing__[self, key]: 
        return key.join["{}"]
    
d = Default[{"foo": "name"}]

print["My {foo} is {bar}".format_map[d]] # "My name is {bar}"
3] the Formatter needs to be subclassed:

import string

class Unformatted:
    def __init__[self, key]:
        self.key = key
    def __format__[self, format_spec]:
        return "{{{}{}}}".format[self.key, ":" + format_spec if format_spec else ""]

class Formatter[string.Formatter]:
    def get_value[self, key, args, kwargs]:
        if isinstance[key, int]:
            try:
                return args[key]
            except IndexError:
                return Unformatted[key]
        else:
            try:
                return kwargs[key]
            except KeyError:
                return Unformatted[key]


f = Formatter[]
s1 = f.vformat["My {0} {1} {foo:

Bài Viết Liên Quan

Chủ Đề