Skip to content Skip to sidebar Skip to footer

Extracting A Substring From A String In Python Based On Delimiter

I have an input string like:- a=1|b=2|c=3|d=4|e=5 and so on... What I would like to do is extract d=4 part from a very long string of similar pattern.Is there any way to get a

Solution 1:

You can use regex here :

>>>data = 'a=1|b=2|c=3|d=4|e=5'>>>var = 'd'>>>output = re.search('(?is)('+ var +'=[0-9]*)\|',data).group(1)>>>print(output)
'd=4'

Or you can also use split which is more recommended option :

>>>data = 'a=1|b=2|c=3|d=4|e=5'>>>output = data.split('|')>>>print(output[3])
'd=4'

Or you can use dic also :

>>> data = 'a=1|b=2|c=3|d=4|e=5'
>>> output = dict(i.split('=') for i in data.split('|'))
{'a': '1', 'b': '2', 'c': '3', 'd': '4', 'e': '5'}
>>> output ['d']
'4'

Solution 2:

Construct a dictionary!

>>>s = 'a=1|b=2|c=3|d=4|e=5'>>>dic = dict(sub.split('=') for sub in s.split('|'))>>>dic['d']
'4'

If you want to store the integer values, use a for loop:

>>>s = 'a=1|b=2|c=3|d=4|e=5'>>>dic = {}>>>for sub in s.split('|'):...    name, val = sub.split('=')...    dic[name] = int(val)...>>>dic['d']
4

Solution 3:

You Can try this "startswith" , specific which variable you want the value

string = " a=1|b=2|c=3|d=4|e=5 "array = string.split("|")
 for word in array:
     if word.startswith("d"):
     print word

Post a Comment for "Extracting A Substring From A String In Python Based On Delimiter"