[英]python: variable string formatting
I have a string like below: 我有一个类似下面的字符串:
a = "This is {} code {}"
In later part of my code, I will be formatting the string using args provided to the below function: 在我的代码的稍后部分,我将使用提供给以下函数的args格式化字符串:
def format_string(str, *args):
fmt_str = str.format(*args)
print fmt_str
...
My problem here is that if number of args provided to the function format_string
is either lesser or more than the required, I get an Exception. 我的问题是,如果提供给函数format_string
的args数量小于或大于所需数量,则会出现异常。 Instead, if args are less, I want it to print empty {} and if the args are more than required, then I want the extra args to be ignored. 相反,如果args少了,我希望它输出空的{},如果args超过要求,那么我希望多余的args被忽略。 i have tried to do this is several ways, but could not avoid the exception. 我尝试过几种方法,但是无法避免例外。 Can anyone help please? 有人可以帮忙吗?
Update: I was able to fix this problem based on the answer provided in this post: Leaving values blank if not passed in str.format 更新:我能够根据本文中提供的答案解决此问题: 如果未在str.format中传递值,则将值留空
This is my implementation: 这是我的实现:
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]
Had to modify the string as follows to use the above BlankFormatter on it: 必须对其进行如下修改以在其上使用上述BlankFormatter:
a = "This is {0} code {1}"
In my format_string function, I used the BlankFormatter to format the string: 在我的format_string函数中,我使用了BlankFormatter格式化字符串:
def format_string(str, *args):
fmt = BlankFormatter()
fmt_str = fmt.format(str,*args)
print fmt_str
...
There are a few different ways to do this, some of which are more or less flexible. 有几种不同的方法可以执行此操作,其中某些方法或多或少具有灵活性。 Perhaps something like this will work for you: 也许这样的事情将为您工作:
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.
num_args
is the number of args
you want, not the number that you passed in. filler
is what to use when there aren't enough args
. num_args
是多少args
你想要的,不是说你在传递的数量。 filler
是时有不够用什么args
。
def formatter(input, *args):
format_count = input.count("{}")
args = list(args) + ["{}"] * (format_count - len(args))
print input.format(*args[:format_count])
formatter("{} {} {}", "1", "2")
formatter("{} {} {}", "1", "2", "3")
formatter("{} {} {}", "1", "2", "3", "4")
1 2 {}
1 2 3
1 2 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.