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

Usunięta treść Dodana treść
niestety nie mam czasu na pisanie, zdejmuje moje WEdycji
Piotr (dyskusja | edycje)
Zaczynam tłumaczyć
Linia 1:
{{WEdycji}}
== Dictionary-based string formatting ==
 
{{Podświetl|py}}
Why did you learn about locals and globals? So you can learn about dictionary-based string formatting. As you recall, regular string formatting provides an easy way to insert values into strings. Values are listed in a tuple and inserted in order into the string in place of each formatting marker. While this is efficient, it is not always the easiest code to read, especially when multiple values are being inserted. You can't simply scan through the string in one pass and understand what the result will be; you're constantly switching between reading the string and reading the tuple of values.
== Formatowanie napisów w oparciu o słowniki ==
 
Dlaczego uczyliśmy się na temat funkcji <tt>locals</tt> i <tt>globals</tt>? Ponieważ teraz możemy się nauczyć formatowania napisów w oparciu o słowniki. Jak już mówiliśmy, regularne formatowanie napisów umożliwia w łatwy sposób wstawiać wartości do napisów. Wartości są wyszczególnione w krotce i w odpowiednim porządku wstawione do napisu, gdzie występuje pole formatujące. O ile jest to skuteczne, nie zawsze tworzy kod łatwy do czytania, zwłaszcza, gdy zostaje wstawianych wiele wartości. Żeby zrozumieć o co chodzi, nie wystarczy po prostu jednorazowo prześledzić napis; trzeba ciągle skakać między czytanym napisem a czytaną krotką wartości.
There is an alternative form of string formatting that uses dictionaries instead of tuples of values.
 
Tutaj mamy alternatywną formę formatowania napisu, a która zamiast krotek wykorzystuje słowniki.
'''Example 8.13. Introducing dictionary-based string formatting'''
 
'''Przykład 8.13. Formatowanie napisów w oparciu o słowniki'''
 
>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
Linia 43 ⟶ 46:
# Now, using dictionary-based string formatting, you insert the value of tag and strattrs into a string. So if tag is 'a', the final result would be '<a href="index.html" title="Go to home page">', and that is what gets appended to self.pieces.
 
{{Uwaga|
Important
Using dictionary-based string formatting with locals is a convenient way of making complex string formatting expressions more readable, but it comes with a price. There is a slight performance hit in making the call to locals, since locals builds a copy of the local namespace.
}}
 
<noinclude>