Home > Software design >  Replace before and after inside string with elements from a list
Replace before and after inside string with elements from a list

Time:02-26

given a string like:

strng = 'http://example.com/example/xyz?abc1234'

I want to replace everything between the last "/" and "?", i.e. replace the "xyz" part, with elements from a list, like:

lst = ['apple', 'banana', 'carrot']

so that I can do like:

for element in list:
    print(strng)

and it returns

http://example.com/example/apple?abc1234
http://example.com/example/banana?abc1234
http://example.com/example/carrot?abc1234

CodePudding user response:

You could replace "xyz" with a placeholder and use str.format:

strng = strng.replace('/xyz?', '/{}?')
for item in lst:
    print(strng.format(item))

Output:

http://example.com/example/apple?abc1234
http://example.com/example/banana?abc1234
http://example.com/example/carrot?abc1234

CodePudding user response:

strng = 'http://example.com/example/xyz?abc1234'
lst = ['apple', 'banana', 'carrot']

for item in lst:
    newstring = strng.replace('xyz',item)
    print (newstring)
  • Related