3

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 substring based on starting point delimter and ending point delimiter?

Such that, I can start from 'd=' and search till '|' to extract its value.Any insights would be welcome.

0

3 Answers 3

5

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'
Sign up to request clarification or add additional context in comments.

6 Comments

i[0]:i[2] won't work for substrings like 'foo=123'.
@timgeb please check !
Yeah, that works. But now you have to call split on = twice, that's why I used a for loop for the dictionary that stores the integers,
@timgeb absolutely, I can also use dict() to achieve the same, should I ?
Yes, the dict constructor takes an iterable of 2-element tuples, and split on = will produce these tuples.
|
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

2 Comments

I could very well be misinterpreting but, OP states that he needs it as a substring, not to access the value in some way.
Hi @Mayank Jha if this or any answer has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.