Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expand a string within a string in python?

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)?

like image 705
pradyuman Avatar asked Jun 12 '15 23:06

pradyuman


2 Answers

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']
like image 88
Tuan Anh Hoang-Vu Avatar answered Oct 20 '22 00:10

Tuan Anh Hoang-Vu


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
like image 31
Namit Singal Avatar answered Oct 20 '22 00:10

Namit Singal