Python字符串格式化增量更改

时间:2014-12-10 01:05:30

标签: python string string-formatting

def foo(string, **kwargs):
  return string % kwargs  # simplified a much more complex SQL query function with argument binding.

string = '%(a)s %(b)s.'
print foo(string %{'a': 'Hello'}, b='world')

我想实现这一目标'%(a)s%(b)s' => '你好%(b)s' => ' Hello world' (而不是'%(a)s%(b)s' =>' Hello world'一气呵成。)

在python中有没有让它工作?

1 个答案:

答案 0 :(得分:4)

只需加倍%

string = '%(a)s %%(b)s.'

如果您想使用新的字符串格式规范,那么您可以类似地加倍大括号:

def foo(string, **kwargs):
  return string.format(**kwargs ) # simplified a much more complex SQL query function with argument binding.

string = '{a} {{b}}.'
print foo(string.format(a='Hello'), b='world')

prints: 
Hello world.