2

Does anyone know how I could best replace all instances of [word] in a text with %s and then build a list or tuple of those [word]s?

Basically, I'm generating PDFs - the text of the PDF I am storing in a TextField in a database - let's say it looks like:

"Hello [patient], you had a study on [date..."

when I generate the PDF on the fly, I want to pass the PDF generator:

"Hello %s, you had a study on %s"%(patient,date)

I don't really feel comfortable with regex. I was reading up on sub and match - but I was wondering if there was a way I could replace the [words] and build the tuple in one line of code.

3 Answers 3

3

You can do this without a regex. Consider:

>>> tgt="Hello [patient], you had a study on [date]"
>>> template=tgt.replace('[', '{').replace(']', '}')
>>> data={'patient':'Bob', 'date':'10/24/2013'}
>>> template.format(**data)
'Hello Bob, you had a study on 10/24/2013'
Sign up to request clarification or add additional context in comments.

2 Comments

wow very nice in that it avoids the regex, but is there a way to build out the list automatically - maybe I can think of something now that i'm more awake
Actually, I could have a hard-coded dict in my django view - w/ all 30 or so possible [word]s that can be selected - something like {'patient': pat.name, 'date', exam.date,'ssn':pat.ssn...} Where pat and ex are django model instances - your code will probably do the trick
1

Please try this pattern:

>>> import re
>>> input = "Hello [patient], you had a study on [date 10-10-16]."
>>> re.sub('\[[^\]]+]', '%s', input)
'Hello %s, you had a study on %s.'

Comments

0

Same solution using re.sub but with different pattern:

>>> inp = "Hello [patient], you had a study on [date]."
>>> 
>>> re.sub(r'\[.*?\]', '%s', inp)
'Hello %s, you had a study on %s.'

If you are willing to replace those params with values from a data object like dictionary for instance:

>>> data
{'date': '10/24/2013', 'patient': 'Bob'}

Then I would do it this way:

>>> inp = "Hello [patient], you had a study on [date]."
>>> data
{'date': '10/24/2013', 'patient': 'Bob'}
>>>
>>> pat = re.compile(r'\[(?P<param>.*?)\]')
>>> pat.sub(lambda m: data[m.group('param')], inp)
'Hello Bob, you had a study on 10/24/2013.'

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.