Python String Formatting - replacing parameters with and incrementation

Viewed 1637

Given the following string template and desired result, is there a simple (one-liner-type) way in Python to achieve this? I would want id to be incremented after/before a replacement.

"fruit-{id} fruit-{id} fruit-{id}"
"fruit-1 fruit-2 fruit-3"

Update: I realize I did not describe the problem very well and did not pick a good example. The template(s) are not usually regular like the fruit example.

It could be like...

"Lorem{id} ipsum dolor{id} sit amet, consectetur adipiscing elit{id}, sed do eiusmod{id} tempor incididunt..." 

...where it is unclear how many id's there will be in the string.

3 Answers

In this case format() is your friend.

Usage

Input -> '{} {}'.format('one', 'two') | Output -> one two

In your case you can use it by doing

string = "fruit-{} fruit-{} fruit-{}".format(1, 2, 3)
print(string)

Outputs fruit-1 fruit-2 fruit-3

If your string is always in the format "fruit-{id} fruit-{id} fruit-{id}"then you can't use the builtin str.format because it relies on the variables being different. You would have to implement your own format function, something like this (using the re module):

def format_str(s, target="{id}"):
    i = 1
    while target in s:
        s = re.subn(target, str(i), s, count=1)[0]
        i += 1
    return s
import re

list_of_ids = ['1','2','3','4','5']

list_of_fruits = [re.sub('id',nos,'fruit-id') for nos in list_of_ids]
//['fruit-1', 'fruit-2', 'fruit-3' ...]

You can use a list comprehension and regex to replace items. To reverse it:

[re.sub('[0-9]','id',fruit) for fruit in list_of_fruits]
Related