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,
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
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 –
Tadhg, ich bekomme es endlich Danke – 7alman