3

I wanted to extract the date from the given string on the basis of tag.

My string is -

DATE: 7/25/2017 DATE OPENED: 7/25/2017 RETURN DATE: 7/26/2017 
NUMBER: 201707250008754 RATE:  10.00

I want something like this - If I give "DATE" it should return 7/25/2017 only

if I give "RETURN DATE" it should return 7/26/2017

if I give the "NUMBER" it should return 201707250008754 and so on.

How we can achieve this in Python 2.7 (Note: Dates and numbers are always random in string"

2
  • Please don't add the python 3 tag if your question is specific to python 2. Commented Jun 1, 2018 at 17:05
  • I'd start with writing some code. What have you attempted, so far? Commented Jun 1, 2018 at 17:08

2 Answers 2

3

You can create a dictionary from the string's contents with re:

import re
s = 'DATE: 7/25/2017 DATE OPENED: 7/25/2017 RETURN DATE: 7/26/2017 NUMBER: 201707250008754 RATE: 10.00'
results = re.findall('[a-zA-Z\s]+(?=:)|[\d/\.]+', s)
d = dict([re.sub('^\s+', '', results[i]), results[i+1]] for i in range(0, len(results), 2))
for i in ['DATE', 'RETURN DATE', 'NUMBER']:
   print(d[i])

Output:

7/25/2017
7/26/2017
201707250008754
Sign up to request clarification or add additional context in comments.

Comments

1

Use dict to map key (eg: 'DATE' ) to its value.

import re
s = '''DATE: 7/25/2017 DATE OPENED: 7/25/2017 RETURN DATE: 7/26/2017 NUMBER: 201707250008754 RATE:  10.00'''

items = re.findall('\s*(.*?)\:\s*([0-9/.]*)',s)
#[('DATE', '7/25/2017'), ('DATE OPENED', '7/25/2017'), ('RETURN DATE', '7/26/2017'), ('NUMBER', '201707250008754'), ('RATE', '10.00')]

info = dict(items)
#{'DATE': '7/25/2017', 'DATE OPENED': '7/25/2017', 'RETURN DATE': '7/26/2017', 'NUMBER': '201707250008754', 'RATE': '10.00'}


for key in ['DATE', 'RETURN DATE', 'NUMBER']:
    print(info[key])

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.