Using punctuation in python format strings

So, I am confused about the .format mechanism in python. (I am currently using 2.7.6)

So this obviously works:

>>> "hello {test1}".format(**{'test1': 'world'})
'hello world'

as well as:

>>> "hello {test_1}".format(**{'test_1': 'world'})
'hello world'

but not one of them:

>>> "hello {test:1}".format(**{'test:1': 'world'})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'test'

neither

>>> "hello {test.1}".format(**{'test.1': 'world'})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'test'

Job.

But for some reason, the following:

>>> "hello {test:1}".format(**{'test': 'world'})
'hello world'

So it seems that the variable names in the replaced string cannot contain colons :or periods .. Is there any way to avoid these characters? The lines that I am looking for for replacement from the dictionary sometimes have periods or both periods or colons.

+4
source share
3 answers

, - . , . , , .

class Computer(object):
    def __init__(self,IP):
        self.IP = IP

-

list_comps = [Computer(name,"192.168.1.{}".format(IP)) for IP in range(12)]

for comp in list_comps:
    frobnicate(comp) # do something to it
    print("Frobnicating the computer located at {comp.IP}".format(comp=comp))

Frobnicating the computer located at 192.168.1.0
Frobnicating the computer located at 192.168.1.1
Frobnicating the computer located at 192.168.1.2 # etc etc

, (comp), IP . formatter (.), , , .

, test, ! : , kwarg - . :

>>> x = 12.34567
>>> print("{x:.2f}".format(x))
12.34

.2f : x float . , ! !

+4

, @admith , , python. , , () , .

? .

- , , Formatter - . python parse().. (, {test:6d}, - 6 ), , , parse, , format_spec conversion.

: , , .

import string

class myFormatter(string.Formatter):
    def parse(self, fstring):
        if fstring is None:  # we also get called with the (null) format spec, for some reason
            return
        parts = fstring.split("}")
        for part in parts:
            if "{" in part:
                literal, fieldname = part.split("{")
                yield (literal, fieldname, None, None)
            else:
                yield (part, None, None, None)

:

>>> custom = myFormatter()
>>> custom.format("hello {test:1}", [], **{'test:1': 'world'})
'hello world'

:

print custom.vformat(templatestring, [], valuedict)
+2

, ?

replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
0

Source: https://habr.com/ru/post/1526238/


All Articles