2016-04-10 7 views
0

Ich kann nicht verstehen, warum der erste Code nicht funktioniert, es ist die gleiche Sache wie die zweite.Python str.format, Warum machen beide Methoden nicht dasselbe?

(I durch ein Buch arbeite und ich nicht, warum mein Code funktioniert nicht)

My Code: 
# My Code Snippet 

x = float(13424) 

formatr = "10.4f" 

stringToBeFormatted = "<td align='right'>{0:formatr}</td>".format(x) 

print(stringToBeFormatted) 



# Book's Code Snippet 


x = float(13424) 

formatr = "10.4f" 

stringToBeFormatted = "<td align='right'>{{0:{0}}}</td>".format(formatr) 

print(stringToBeFormatted.format(x)) 



#output should be: 

<td align='right'>13434.0000</td> 


My Code gives an error: 

Why don't both code snippets work the same way? I don't see how they differ. 

Book's code just inputs the formatr inside the str.format by the field argument, 
and I just input it directly. 

Vielen Dank für jede Hilfe,

Antwort

2

das zweite Beispiel {{0:{0}}} hat {0} anstelle von das Format spec, so ersten Mal ist es die Spezifikation formatiert ist, in Position gebracht und eine Schicht aus {} wird aus dem Format mit doppelter Markierung {{}} entfernt:

>>> "{{0:{0}}}".format(formatr) 
'{0:10.4f}' 

dann das zweite Mal, das das Feld in Position gebracht wird:

>>> '{0:10.4f}'.format(x) 
'13424.0000' 

die Formatierung zu tun in einem Rutsch Sie die Spezifikation als {formatr} und fügen hinzu, dass als Argument an .format() angeben müssen:

>>> "{0:{formatr}}".format(x,formatr=formatr) 
'13424.0000' 

oder als Positions Argument angegeben:

>>> "{0:{1}}".format(x,formatr) 
'13424.0000' 
+0

Dank Tadhg, sollte aber nicht noch mein Code arbeiten? Die formatr-Variable speichert die Formatspezifikation "10.4f" und verwendet diese direkt in der .format-Methode. Es schreibt im Grunde "{0: 10.4f}". Format (x), wie Sie es in Ihrem zweiten Snippet geschrieben haben. – 7alman

+0

Die Variable wird nie verwendet, nur ihr variabler Name in der Zeichenfolge selbst! Sie könnten '.replace (" formatr ", formatr) verwenden, um alle Vorkommen des _string_' formatr 'durch die _variable_ 'formatr' zu ersetzen oder" ... {0: "+ formatr +"} ... "' to direkt den Inhalt der _variable_ in die Zeichenkette einfügen, aber es als Formatvariable zu spezifizieren ist definitiv der beste Weg zu gehen –

+0

Tadhg, ich bekomme es endlich Danke – 7alman

-1

In Ihrem Beispiel kann das python-Interpreter nicht 01 identifizierenformatr innerhalb stringToBeFormatted als Variable und kann daher nicht aufgelöst werden. Es würde funktionieren, wenn Sie die formatr string (dessen Inhalt) in den stringToBeFormatted gestellt wie:

x = float(13424) 

stringToBeFormatted = "<td align='right'>{0:10.4f}</td>".format(x) 

print(stringToBeFormatted.format(x)) 
+0

Sie haben einfach hart in den Wert anstelle der Formatierung in der Spezifikation codiert wie das Beispiel aus dem Buch tut. –

Verwandte Themen