RA.
RA.

Reputation: 1029

Templates with argument in string formatting

I'm looking for a package or any other approach (other than manual replacement) for the templates within string formatting.

I want to achieve something like this (this is just an example so you could get the idea, not the actual working code):

text = "I {what:like,love} {item:pizza,space,science}".format(what=2,item=3)
print(text)

So the output would be:

I love science

How can I achieve this? I have been searching but cannot find anything appropriate. Probably used wrong naming terms.


If there isnt any ready to use package around I would love to read some tips on the starting point to code this myself.

Upvotes: 1

Views: 1032

Answers (4)

RA.
RA.

Reputation: 1029

Since no one have provided an appropriate answer that answers my question directly, I decided to work on this myself.

I had to use double brackets, because single ones are reserved for the string formatting.

I ended up with the following class:

class ArgTempl:
    def __init__(self, _str):
        self._str = _str

    def format(self, **args):
        for k in re.finditer(r"{{(\w+):([\w,]+?)}}", self._str,
                             flags=re.DOTALL | re.MULTILINE | re.IGNORECASE):
            key, replacements = k.groups()

            if not key in args:
                continue

            self._str = self._str.replace(k.group(0), replacements.split(',')[args[key]])

        return self._str

This is a primitive, 5 minute written code, therefore lack of checks and so on. It works as expected and can be improved easly.

Tested on Python 2.7 & 3.6~

Usage:

test = "I {{what:like,love}} {{item:pizza,space,science}}"
print(ArgTempl(test).format(what=1, item=2))
> I love science

Thanks for all of the replies.

Upvotes: 0

Chamath
Chamath

Reputation: 2044

My be use a list or a tuple for what and item as both data types preserve insertion order.

what = ['like', 'love']
item = ['pizza', 'space', 'science']

text = "I {what} {item}".format(what=what[1],item=item[2])
print(text)    # I like science

or even this is possible.

text = "I {what[1]} {item[2]}".format(what=what, item=item)
print(text)  # I like science

Hope this helps!

Upvotes: 1

dbenarfa
dbenarfa

Reputation: 731

I think using list is sufficient since python lists are persistent

what = ["like","love"]
items = ["pizza","space","science"]
text = "I {} {}".format(what[1],items[2])
print(text)

output: I love science

Upvotes: 1

PeptideWitch
PeptideWitch

Reputation: 2349

Why not use a dictionary?

options = {'what': ('like', 'love'), 'item': ('pizza', 'space', 'science')}
print("I " + options['what'][1] + ' ' + options['item'][2])

This returns: "I love science"

Or if you wanted a method to rid yourself of having to reformat to accommodate/remove spaces, then incorporate this into your dictionary structure, like so:

options = {'what': (' like', ' love'), 'item': (' pizza', ' space', ' science'), 'fullstop': '.'}
print("I" + options['what'][0] + options['item'][0] + options['fullstop'])

And this returns: "I like pizza."

Upvotes: 0

Related Questions