Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python格式字符串中标点符号的使用_Python_Python 2.7_Formatting - Fatal编程技术网

python格式字符串中标点符号的使用

python格式字符串中标点符号的使用,python,python-2.7,formatting,Python,Python 2.7,Formatting,所以我对python中的.format机制感到困惑。(我目前正在使用2.7.6) 因此,这显然有效: >>> "hello {test1}".format(**{'test1': 'world'}) 'hello world' 而且: >>> "hello {test_1}".format(**{'test_1': 'world'}) 'hello world' 但两者都不是: >>> "hello {test:1}".format(**

所以我对python中的.format机制感到困惑。(我目前正在使用2.7.6)

因此,这显然有效:

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

>>> "hello {test_1}".format(**{'test_1': 'world'})
'hello world'
但两者都不是:

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

因此,被替换字符串中的变量名似乎不能包含冒号
或句点
。有没有办法摆脱这些角色?我希望从字典中替换的字符串偶尔会有句点或同时有句点或冒号

这是因为您可以使用format mini语言访问对象的属性。例如,我经常在自己的自定义类工作中使用它。假设我为每台需要操作的计算机定义了一个类

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
,并使用它。在您的示例中,您为格式化程序提供了类似于属性访问器(
)的内容,因此它尝试访问在访问器之前给定的对象,然后查找其定义的属性

您的最后一个示例之所以有效,是因为它正在查找
test
,并且找到了它!
符号是格式化程序特有的,因为它标志着
kwarg
的结束和格式迷你语言的开始。例如:

>>> x = 12.34567
>>> print("{x:.2f}".format(x))
12.34
后面的
.2f
告诉字符串格式化程序将参数
x
视为
浮点值
,并在小数点后两位数处截断。这是,我强烈建议你好好看一看,并把它书签起来,以备将来使用!这很有帮助

嗯,你查过了吗


@adsmith没有提到的是格式名称必须是有效的python标识符。因此可以包含下划线和数字,但不能包含(带引号的)冒号,因为它不能是标识符的一部分

你能做什么?我将研究重命名字典对象,或者调整格式字符串以使用位置参数

如果由于数据的性质,这些都是不切实际的,或者如果您只是想按自己的方式来做,那么这个类就是您的朋友它允许您使用自己的
parse()
方法覆盖python的模板字符串解析器。
因为您实际上似乎不需要大括号内的格式规范(比如
{test:6d}
将某些内容填充到6个空格),您所要做的就是构造一个
parse
方法,该方法将整个格式字符串作为字段名,并使用空的
format\u 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)
或者最好是这样:

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

谢谢@adsmith。我理解您所演示的用例,但这是否意味着无法避开那些
?在我可以使用
.format()
@notlink之前,我是否需要以某种方式重新格式化我的文本以删除它们?老实说,我不知道!我从未尝试在格式字符串中转义
。我的直觉是说你不能,但是试试看,然后找出答案@notlink Oops,看起来这个用例已经被记录下来了。“因为arg_name不是以引号分隔的,所以无法在格式字符串中指定任意字典键(例如字符串“10”或“:-]”。”@notlink只是为了好玩,请打印“你好”{test:20},你好吗?”。格式(**{test':'World'),您将看到
{test 1}
真正在做什么。谢谢@alexis。”。在短期内,我想我会做一些类似于
“{test.1}”的事情。替换('.','''''.').format(**{test_1':'hello'})
,但就我的目的而言,深入研究
parse()
可能是一个更好的长期解决方案。我感谢你的建议。
print custom.vformat(templatestring, [], valuedict)