How to expand a string within a string in python?

3.4k Views Asked by At

I have a string that looks like this:

1 | xxx | xxx | xxx | yyy*a*b*c | xxx

I want to expand the yyy*a*b*c part so that the string looks like this:

1 | xxx | xxx | xxx | yyya | yyyb | yyyc | xxx

I actually have a big file with a delimiter between these strings. I have parsed the file into a dictionary that looks like this:

{'1': ['xxx' , 'xxx', 'xxx', 'yyy*a*b*c', 'xxx' ], '2': ['xxx*d*e*f', ...,  'zzz'], etc}

And I need to have that yyy*a*b*c and xxx*d*e*f part be replaced with additional items in the list.

How can I do this in python 3? Should I expand everything in the string before I parse it into a dictionary or after I parse it into a dictionary (and how)?

3

There are 3 best solutions below

0
On BEST ANSWER

You can do this using split and simple list comprehension:

def expand_input(input):
    temp = input.split("*")
    return [temp[0]+x for x in temp[1:]]

print(expand_input("yyy*a*b*c"))
>>> ['yyya', 'yyyb', 'yyyc']
0
On

You should be doing it while parsing data from the file, Just pass each of the arguments through this function while adding to list, adding to @tuananh answer :-

def expand_input(input):
    temp = input.split("*")
    return [temp[0]+x for x in temp[1:]] if len(temp)>1 else input
0
On

process will take in a list like:

['xxx', 'xxx', 'yyy*a*b*c', 'xxx*d*e*f']

and give back the full list with the correct terms expanded:

def expand(s):
    """
    expand('yyy*a*b*c') --> ['yyya', 'yyyb', 'yyyc']
    expand('xxx') --> ['xxx']
    """

    if "*" not in s:
        return s
    base, suffixes = s.split("*")
    return [base + suffix for suffix in suffixes]

def process(strings):
    result = []
    for s in strings:
        result.extend(s)
    return result