2016-10-25 4 views
-1

again :)Format() Funktion in Python - Verwendung mehrerer geschweiften Klammern {{{}}}

ich dieses Stück Code gefunden

col_width=[13,11] 
header=['First Name','Last Name'] 

format_specs = ["{{:{}}}".format(col_width[i]) for i in range(len(col_width))] 
lheader=[format_specs[i].format(self.__header[i]) for i in range(nb_columns)] 

Wie Python werten diese Aussage? Warum verwenden wir drei {wenn wir in jeder Iteration ein Element formatieren müssen?

+2

Warum markieren Sie dies mit einem Python 2 und einem Python 3-Tag? Welches ist es? ist es überhaupt wichtig? Bitte verwenden Sie keine unangemessenen Tags. –

+0

Lesen Sie die [docs] (https://docs.python.org/3/library/string.html#formatstrings). – user2357112

+0

Vielen Dank :) –

Antwort

0

Wenn Sie {{}} tun, überspringt Python den Ersatz von {} und macht es zum Teil string. Im Folgenden finden Sie die Probe Beispiel zu erklären:

>>> '{{}}'.format(3) # with two '{{}}' 
'{}' # nothing added to the string, instead made inner `{}` as the part of string 
>>> '{{{}}}'.format(3) # with three '{{{}}}' 
'{3}' # replaced third one with the number 

In ähnlicher Weise wird Ihr Ausdruck Auswertung als:

>>> '{{:{}}}'.format(3) 
'{:3}' # during creation of "format_specs" 

Einzelheiten siehe: Format String Syntax Dokument.

+1

Vielen Dank :) –

Verwandte Themen