0

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.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
Navya Vaishnavi
  • 59
  • 1
  • 2
  • 7
  • 1
    possible duplicate of [Python string formatting: % vs. .format](http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format) – thefourtheye Feb 01 '15 at 06:11

4 Answers4

2
>>> "{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'
John1024
  • 109,961
  • 14
  • 137
  • 171
1

Here's an example utilising 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
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

UPDATE:

"{1} calls {0} and {2}".format("hari", "ashok", "x")
>>> 'ashok calls hari and x'
Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123
Sazid
  • 2,747
  • 1
  • 22
  • 34
0

Function to return a formatted string in 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
piyushj
  • 1,546
  • 5
  • 21
  • 29