python:变量字符串格式
我有一个字符串,如下所示:python:变量字符串格式,python,string,format,Python,String,Format,我有一个字符串,如下所示: a = "This is {} code {}" 在代码的后面部分,我将使用提供给以下函数的参数格式化字符串: def format_string(str, *args): fmt_str = str.format(*args) print fmt_str ... 我这里的问题是,如果提供给函数format\u string的参数数量小于或大于所需数量,我会得到一个异常。 相反,如果arg较少,我希望它打印空{},如果arg多于所需,那么我
a = "This is {} code {}"
在代码的后面部分,我将使用提供给以下函数的参数格式化字符串:
def format_string(str, *args):
fmt_str = str.format(*args)
print fmt_str
...
我这里的问题是,如果提供给函数format\u string
的参数数量小于或大于所需数量,我会得到一个异常。
相反,如果arg较少,我希望它打印空{},如果arg多于所需,那么我希望忽略额外的arg。
我试过几种方法来做到这一点,但无法避免例外。有人能帮忙吗
更新:根据本文提供的答案,我能够解决这个问题:
这是我的实现:
class BlankFormatter(Formatter):
def __init__(self, default=''):
self.default = default
def get_value(self, key, args, kwargs):
if isinstance(key, (int, long)):
try:
return args[key]
except IndexError:
return ""
else:
return kwargs[key]
必须按如下方式修改字符串以在其上使用上述BlankFormatter:
a = "This is {0} code {1}"
在我的format_string函数中,我使用BlankFormatter格式化字符串:
def format_string(str, *args):
fmt = BlankFormatter()
fmt_str = fmt.format(str,*args)
print fmt_str
...
有几种不同的方法可以做到这一点,其中一些或多或少都是灵活的。也许这样的事情对你有用:
from __future__ import print_function
def transform_format_args(*args, **kwargs):
num_args = kwargs['num_args'] # required
filler = kwargs.get('filler', '') # optional; defaults to ''
if len(args) < num_args: # If there aren't enough args
args += (filler,) * (num_args - len(args)) # Add filler args
elif len(args) > num_args: # If there are too many args
args = args[:num_args] # Remove extra args
return args
args1 = transform_format_args('cool', num_args=2)
print("This is {} code {}.".format(*args1)) # This is cool code .
args2 = transform_format_args('bird', 'worm', 'fish', num_args=2)
print("The {} ate the {}.".format(*args2)) # The bird ate the worm.
args3 = transform_format_args(num_args=3, filler='thing')
print("The {} stopped the {} with the {}.".format(*args3))
# The thing stopped the thing with the thing.
from\uuuuu future\uuuuu导入打印功能
def转换格式参数(*参数,**kwargs):
num_args=kwargs['num_args']#必需
filler=kwargs.get('filler','')#可选;默认为“”
如果len(args)num_args:#如果args太多
args=args[:num_args]#删除额外的args
返回参数
args1=transform\u format\u args('cool',num\u args=2)
打印(“这是{}代码{}..format(*args1))#这是很酷的代码。
args2=transform\u format\u args('bird','worm','fish',num\u args=2)
print({}吃了{}..format(*args2))#鸟吃了虫子。
args3=transform\u format\u args(num\u args=3,filler='thing')
打印({}使用{}..format(*args3))停止{}
#那东西用那东西挡住了那东西。
num_args
是您想要的args
的数目,而不是您传入的数目filler
是在没有足够的args
时使用的方法,您尝试了哪些“方法”,并且您可以更具体地说明“无法避免异常”的问题吗?可能重复Hi,我在这里使用的是列表,而不是用于格式化的dict。我的字符串中没有键。您提到的帖子提供了一个从dicts中通过键获取值的解决方案。请发布您正在获取的异常以及您尝试过的一些代码。如果args
仅包含一个参数,它是对应于第一个'{}'
还是第二个?如果它包含两个以上的参数,哪些应该保留,哪些应该放弃?所有这一切只是确认'{}'
在该字符串中出现两次。我只是使用这种格式来显示它返回的内容。显然,它将以不同的方式使用。同样,所有这一切只是确认该字符串包含两个'{}'
实例。我看不出这是如何回答这个问题的。我将如何使用它的描述改为实际代码。谢谢!如果我只使用{},我想这是一个很好的解决方案。然而,我实现了一个不同的解决方案,通过向{}添加数字来指示应该考虑哪个位置参数。这样我就能够捕获索引器异常。请看我关于这个问题的最新情况。
from __future__ import print_function
def transform_format_args(*args, **kwargs):
num_args = kwargs['num_args'] # required
filler = kwargs.get('filler', '') # optional; defaults to ''
if len(args) < num_args: # If there aren't enough args
args += (filler,) * (num_args - len(args)) # Add filler args
elif len(args) > num_args: # If there are too many args
args = args[:num_args] # Remove extra args
return args
args1 = transform_format_args('cool', num_args=2)
print("This is {} code {}.".format(*args1)) # This is cool code .
args2 = transform_format_args('bird', 'worm', 'fish', num_args=2)
print("The {} ate the {}.".format(*args2)) # The bird ate the worm.
args3 = transform_format_args(num_args=3, filler='thing')
print("The {} stopped the {} with the {}.".format(*args3))
# The thing stopped the thing with the thing.