在python中返回格式化字符串的函数 [英] Function to return a formatted string in python

查看:53
本文介绍了在python中返回格式化字符串的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个函数,它通过用 args (0...len(args)) 中的 Xth 参数替换 %X 的所有实例来返回格式化的字符串

示例:

simple_format("%1 调用 %0 和 %2", "ashok", "hari")=="hari 调用 ashok 和 %2"

请帮帮我.

解决方案

>>>"{1} 调用 {0} 和 {2}".format( "ashok", "hari", "tom")哈里给阿肖克和汤姆打电话"

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

导入重新def simple_format(*args):s = re.sub(r'%(\d+)', r'{\1}', args[0])返回 s.format(*args[1:])

示例:

<预><代码>>>>simple_format("%1 调用 %0 和 %2", "ashok", "hari", "tom")哈里给阿肖克和汤姆打电话"

A function which returns a formatted string by replacing all instances of %X with Xth argument in args (0...len(args))

Example:

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

Please help me out.

解决方案

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

If you really need the function simple_format, then:

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

Example:

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

这篇关于在python中返回格式化字符串的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆