Zanurkuj w Pythonie/Formatowanie napisów w oparciu o słowniki: Różnice pomiędzy wersjami

Usunięta treść Dodana treść
Piotr (dyskusja | edycje)
Zaczynam tłumaczyć
Piotr (dyskusja | edycje)
Nie podano opisu zmian
Linia 18:
'master of mind, master of body'
 
# Zamiast korzystać z krotki wartości, formujemy napis formatujący, który korzysta ze słownika <tt>params</tt>. Ponadto zamiast prostego pola <tt>%s</tt> w napisie, pole zawiera nazwę w nawiasach klamrowych. Nazwa ta jest wykorzystana jako klucz w słowniku <tt>params</tt> i zostaje zastąpiona odpowiednią wartością, <tt>secret</tt>, w miejscu wystąpienia pola <tt>%(pwd)s</tt>.
# Instead of a tuple of explicit values, this form of string formatting uses a dictionary, params. And instead of a simple %s marker in the string, the marker contains a name in parentheses. This name is used as a key in the params dictionary and subsitutes the corresponding value, secret, in place of the %(pwd)s marker.
# Takie formatowanie może posiadać dowolną liczbę odwołań do kluczy. Każdy klucz musi istnieć w podanym słowniku, ponieważ inaczej formatowanie zakończy się niepowodzeniem i zostanie wyrzucony wyjątek <tt>KeyError</tt>.
# Dictionary-based string formatting works with any number of named keys. Each key must exist in the given dictionary, or the formatting will fail with a KeyError.
# Możesz nawet wykorzystać ten sam klucz dwa razy. Każde wystąpienie zostanie zastąpione odpowiednią wartością.
# You can even specify the same key twice; each occurrence will be replaced with the same value.
 
Zatem dlaczego używać formatowania napisu w oparciu o słowniki? Może to wyglądać na nadmierne wmieszanie słownika z kluczami i wartościami, aby wykonać proste formatowanie napisu. W rzeczywistości jest bardzo przydatne, kiedy już się ma słownik z kluczami o sensownych nazwach i wartościach, jak np. <tt>locals</tt>.
So why would you use dictionary-based string formatting? Well, it does seem like overkill to set up a dictionary of keys and values simply to do string formatting in the next line; it's really most useful when you happen to have a dictionary of meaningful keys and values already. Like locals.
 
'''ExamplePrzykład 8.14. Dictionary-basedFormatowanie stringnapisu formatting inw <tt>BaseHTMLProcessor.py</tt>'''
 
def handle_comment(self, text):
self.pieces.append("<!--%(text)s-->" % locals()) #(1)
 
# Using the built-in locals function is the most common use of dictionary-based string formatting. It means that you can use the names of local variables within your string (in this case, text, which was passed to the class method as an argument) and each named variable will be replaced by its value. If text is 'Begin page footer', the string formatting <nowiki>"<!--%(text)s-->"</nowiki> % locals() will resolve to the string '<!--Begin page footer-->'.
 
'''Example 8.15. More dictionary-based string formatting'''