2

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.

1
  • I edited the question above since I was not precise enough. So far rassar's answer would work the best I think. Commented Nov 23, 2017 at 3:10

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

You can also support an arbitrary amount of elements (id's): repl.it/repls/DimgreyAstonishingBovine
1

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

2 Comments

See my comment on the other answer. You can generate the format string itself on the fly as well as the list of ids.
@user2896976 Gotcha, did not know that variables could be anonymous in string.format. Would have saved a lot of trouble.
1
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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.