Is there a Python function for repeating a string if the string contains a key substring?

Question:

Say I have a simple list such as "apples, bananasx2, orangesx3, pears."

Is there a function that will convert this into "apples, bananas, bananas, oranges, oranges, oranges, pears"?

I’ve tried to write an if loop but I can’t figure out how to identify the number and also repeat the string by that number. This info is currently in dataframe columns but it doesn’t have to be.

Asked By: Ryguy266

||

Answers:

Not sure if thats the fastest, but you could use:

import re    
l = []
for elem in ["apples", "bananasx2", "orangesx3", "pears"]:
    if re.search(".*xd", elem):
        word, occurrence = elem.rsplit("x", 1)
        l += [word] * int(occurrence)
    else:
        l.append(elem)
Answered By: bitflip

I would prefer more elegant code. But it works.

lis = ["apples", "bananasx2", "orangesx3", "pears"]

for index, i in enumerate(lis) :
    if  i[-2:-1] == "x" and i[-1].isnumeric:
        lis[index] = i[:-2]
        for num in range(int(i[-1])-1):
            lis.append(i[:-2])
        
Answered By: Aric a.