Ich bin neu in Python und lesen Sie einfach den folgenden Teil aus Python doc 6.1.3. Format String Syntax:was sind gültige Schlüssel nach Python str.format() Dokumentation
Because arg_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings '10' or ':-]') within a format string.
Was bedeutet das? Kann mir jemand Beispiele geben? Bedeutet dies, dass alle Zahlen in einer Formatzeichenfolge Positionsargumente sind? Also ist "10" das 10. Argument? Für ': -]', ist das so, weil es ']' hat?
Und ich habe auch diese post gesehen.
Die andere Frage ist vom Post
dictionary = {'key1': 'val1', '1': 'val2'}
string1 = 'Interpolating {0[key1]}'.format(dictionary)
print string1
Warum es nicht {0 [ "key1"]} ist? Der Schlüssel 'key1' ist eine Zeichenkette, aber hier, wenn 'key1' benutzt wird, ist es ein Fehler. Ein normaler dict-Index sollte dictionary ['key1'] sein, nicht dictionary [key1]
Und genau wie @BrenBarn in diesem Beitrag geantwortet hat, kann es funktionieren, wenn Nummer 1 als Schlüssel im Wörterbuch verwendet wird.
dictionary = {'key1': 'val1', 1: 'val2'}
string2 = 'Interpolating {0[1]}'.format(dictionary)
print string2
So bin ich verwirrt darüber, was der gültige index_string in einer Format-Zeichenfolge sind
Danke,
fand ich dieses eine wertvolle Ressource sein: https://pyformat.info/#getitem_and_getattr – LJGibbs
«Explicit ist besser als implizit.» Ich halte das Extrahieren, was Werte muss außerhalb des Formatstrings formatiert werden, es sei denn, es offensichtlich tot ist. – 9000