3

lets say I have the following string:

s = """hi my name is 'Ryan' and I like to 'program' in "Python" the best"""

I would like to run a re.sub that would change the following string to:

"""hi my name is '{0}' and I like to '{1}' in "{2}" the best"""

This would let me save content, but have a reference to it so that I could add the original content back in.

note: I use the following code to grab all of the items in quotes so I would loop through this to make reference to the numbers

items = re.findall(r'([\'"])(.*?)\1',s)

So how can I make it so the sub will recognize the number instance so I can create this kind of reference?

1 Answer 1

4

Use re.sub with callback:

>>> import itertools
>>> import re
>>> s = """hi my name is 'Ryan' and I like to 'program' in "Python" the best"""
>>> c = itertools.count(1)
>>> replaced = re.sub(r'([\'"])(.*?)\1', lambda m: '{0}{{{1}}}{0}'.format(m.group(1), next(c)), s)
>>> print(replaced)
hi my name is '{1}' and I like to '{2}' in "{3}" the best

Used itertools.count to generate numbers:

>>> it = itertools.count(1)
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
Sign up to request clarification or add additional context in comments.

3 Comments

I have to go to a class now, but i'll accept your answer when I get back in a couple hours
if I wanted to use other symbols to wrap other than curly brackets, how do I? when I change the code to make it for < those kinds of brackets, i get the following error: File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 151, in sub return _compile(pattern, flags).sub(repl, string, count) File "<stdin>", line 5, in <lambda> KeyError: '<1>'
Try '{0}({1}){0}', {0}*{1}*{0}, .... Curly braces was escaped because of Format String Syntax.

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.