[英]python: variable string formatting
我有一個類似下面的字符串:
a = "This is {} code {}"
在我的代碼的稍后部分,我將使用提供給以下函數的args格式化字符串:
def format_string(str, *args):
fmt_str = str.format(*args)
print fmt_str
...
我的問題是,如果提供給函數format_string
的args數量小於或大於所需數量,則會出現異常。 相反,如果args少了,我希望它輸出空的{},如果args超過要求,那么我希望多余的args被忽略。 我嘗試過幾種方法,但是無法避免例外。 有人可以幫忙嗎?
更新:我能夠根據本文中提供的答案解決此問題: 如果未在str.format中傳遞值,則將值留空
這是我的實現:
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.
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.