x = " \{ Hello \} {0} "
print x.format(42)
Run Code Online (Sandbox Code Playgroud)
给我 : Key Error: Hello\\
我想打印输出: {Hello} 42
我已经阅读了python文档中的示例,但仍然无法弄清楚这个方法的含义.有人可以帮忙吗?以下是python文档中的两个示例
>>> from collections import defaultdict
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
Run Code Online (Sandbox Code Playgroud)
和
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
Run Code Online (Sandbox Code Playgroud)
参数int和list用于什么?
是否可以使用高级字符串格式化方法进行部分字符串格式化,类似于字符串模板safe_substitute()函数?
例如:
s = '{foo} {bar}'
s.format(foo='FOO') #Problem: raises KeyError 'bar'
Run Code Online (Sandbox Code Playgroud) 我遇到了一个相当简单的问题,我无法想出一个优雅的解决方案.
我正在str.format一个函数中创建一个字符串,该函数在一个dict替换中传递以用于格式.我想创建字符串并使用值格式化它们,如果它们被传递,否则将它们留空.
防爆
kwargs = {"name": "mark"}
"My name is {name} and I'm really {adjective}.".format(**kwargs)
Run Code Online (Sandbox Code Playgroud)
应该回来
"My name is mark and I'm really ."
Run Code Online (Sandbox Code Playgroud)
而不是抛出KeyError(如果我们不做任何事情会发生什么).
令人尴尬的是,我甚至无法为这个问题提出一个不优雅的解决方案.我想我可以通过不使用来解决这个问题str.format,但如果可能的话,我宁愿使用内置(主要是我想要的).
注意:我事先并不知道将使用哪些密钥.如果有人包含一把钥匙但是没有把它放在kwargs dict中,我试图优雅地失败.如果我100%准确地知道将要查找哪些键,我只需填充所有键并完成它.
有没有办法使用python string.format,这样当索引丢失时不会抛出异常,而是插入一个空字符串.
result = "i am an {error} example string {error2}".format(hello=2,error2="success")
Run Code Online (Sandbox Code Playgroud)
在这里,结果应该是:
"i am an example string success"
Run Code Online (Sandbox Code Playgroud)
现在,python抛出了一个keyerror并停止格式化.是否有可能改变这种行为?
谢谢
编辑:
存在Template.safe_substitute(即使使模式保持原样而不是插入空字符串),但对于string.format可能没有类似的东西
期望的行为类似于php中的字符串替换.
class Formatter(string.Formatter):
def get_value(self,key,args,kwargs):
try:
if hasattr(key,"__mod__"):
return args[key]
else:
return kwargs[key]
except:
return ""
Run Code Online (Sandbox Code Playgroud)
这似乎提供了期望的行为.
我正在编写一个 PyTest 插件,其中使用此函数实现了不同的自定义标记:
def pytest_configure(config):
config.addinivalue_line("markers", "title(a_title): a title to present the test case")
Run Code Online (Sandbox Code Playgroud)
然后,使用这些标记为 jUnit 输出中的每个测试用例添加自定义属性。
现在,由于我发现自己经常使用parametrize标记,因此我想用参数化标记中定义的参数值填充标记的一部分。
这是我想要实现的目标的一个例子。代码如下:
class TestClass:
@pytest.mark.parametrize("param", ["value1", "value2"])
@pytest.mark.title(f"This test case checks that param is {param}")
def test_simple_test_case(self, param):
pass
Run Code Online (Sandbox Code Playgroud)
我希望 XML 输出像这样填充:
<testcase classname="test_example.TestClass" name="test_simple_test_case[value1]" time="0.001">
<properties>
<property name="title" value="This test case checks that param is value1"/>
</properties>
</testcase>
<testcase classname="test_example.TestClass" name="test_simple_test_case[value2]" time="0.001">
<properties>
<property name="title" value="This test case checks that param is value2"/>
</properties>
</testcase>
<testcase classname="test_example.TestClass" name="test_simple_test_case[value3]" time="0.001"> …Run Code Online (Sandbox Code Playgroud) EDITED
我必须使用字典中的值格式化字符串,但字符串已包含大括号.例如:
raw_string = """
DATABASE = {
'name': '{DB_NAME}'
}
"""
Run Code Online (Sandbox Code Playgroud)
但是,当然,raw_string.format(my_dictionary)KeyErro的结果.
有没有办法使用不同的符号.format()?
这不是重复的如何在python字符串中打印文字大括号字符并在其上使用.format?因为我需要保持大括号,并使用不同的分隔符.format.
我有一个像这样的字符串:
my_string = '{general_setting} ... {specific_setting}'
Run Code Online (Sandbox Code Playgroud)
general_setting对于整个程序(即数据库密码)是相同的,而specific_setting可以在整个程序中变化.有没有办法将一个字符串格式化两次,首先插入general_setting然后预先准备好的字符串以便稍后插入specific_setting?
我确信之前一定会被问过,但我能找到的只是关于如何多次插入相同VALUE的问题,而不是关于如何在不同时间插入不同值的问题.
python ×8
format ×3
string ×3
cheetah ×1
curly-braces ×1
defaultdict ×1
dictionary ×1
missing-data ×1
pytest ×1
python-3.x ×1
syntax ×1