Home > Enterprise >  How to create function that cope with many items in string.format()?
How to create function that cope with many items in string.format()?

Time:12-24

I don't know how to write this code in python.

def text_gen(text,var):
    output = text.format(var[0]=var[0],var[1]=var[1], ....,var[n]=var[n])
    return output

text is string i.e. text = 'I love eating {a}'
var is list of variables i.e. var = [a,b,c]

this function should work like this below

text   = 'I {verb} {obj}'
verb   = 'love'
obj    = 'eating'
var    = [verb,obj]

text_gen(text=text,var=var)

It should return

'I love eating'

CodePudding user response:

I'm not convinced that this is really what you want but it takes your defined input and gives the output you require:

text = 'I {verb} {obj}'
verb = 'love'
obj = 'eating'
var = [verb, obj]

def text_gen(text, var):
    return text.replace('{verb}', var[0]).replace('{obj}', var[1])

print(text_gen(text, var))

CodePudding user response:

If you want separate line for each variable in var then:

output = [text.format(a=v) for v in var]

If you want to format a strings with different number of values then pass a string with numbers as the intended variable to format. For example:

line = 'I love to eat {0}, and {1}'
line2 = 'I like colors {0}, {1}, {2}'

fruit = ['apple', 'orange']
colors = ['black', 'white', 'blue']

def text_gen(text, var):
  return text.format(*var)

Be aware that number of values in var could exceed the number of placeholders in the string, but the string cannot contain more placeholders than the number of variables in var.

  • Related