函数返回python中的格式化字符串

2024-09-28 01:29:38 发布

您现在位置:Python中文网/ 问答频道 /正文

一种函数,通过将args (0...len(args))%X的所有实例替换为Xth参数,返回格式化字符串

示例:

simple_format("%1 calls %0 and %2", "ashok", "hari")=="hari calls ashok and %2"

请帮帮我。在


Tags: and实例函数字符串format示例参数len
3条回答
>>> "{1} calls {0} and {2}".format( "ashok", "hari", "tom")
'hari calls ashok and tom'

如果您确实需要函数simple_format,那么:

^{pr2}$

示例:

>>> simple_format("%1 calls %0 and %2", "ashok", "hari", "tom")
'hari calls ashok and tom'

下面是一个使用string.Template的示例:

from string import Template

def simple_format(text, *args):
    class T(Template):
        delimiter = '%'
        idpattern = '\d+'
    return T(text).safe_substitute({str(i):v for i, v in enumerate(args)})

simple_format("%1 calls %0 and %2", "ashok", "hari")
# hari calls ashok and %2

更新:

"{1} calls {0} and {2}".format("hari", "ashok", "x")
>>> 'ashok calls hari and x'

相关问题 更多 >

    热门问题