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

时间:2015-02-01 06:08:03

标签: python python-2.7 string-formatting

通过在%X

中用Xth参数替换args (0...len(args))的所有实例来返回格式化字符串的函数

示例:

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

请帮帮我。

4 个答案:

答案 0 :(得分:1)

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

如果你真的需要函数simple_format,那么:

import re
def simple_format(*args):
    s = re.sub(r'%(\d+)', r'{\1}', args[0])
    return s.format(*args[1:])

示例:

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

答案 1 :(得分:1)

以下是使用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

答案 2 :(得分:0)

<强>更新

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

答案 3 :(得分:0)

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

def simple_format(format, *args):
"""
Returns a formatted string by replacing all instances of %X with Xth argument in args (0...len(args))
e.g. "%0 says hello", "ted" should return "ted says hello"
"%1 says hello to %0", ("ted", "jack") should return jack says hello to ted etc.
If %X is used and X > len(args) it is returned as is.
"""
pass
count = 0
for name in args:
    format = format.replace("%" + str(count), name)
    count = count + 1
return format