stupid newbie question about string and re

Steve Holden sholden at holdenweb.com
Fri Jan 18 10:07:04 EST 2002


"Bertrand Geston" <bergeston at yahoo.fr> wrote in message
news:df3b00ed.0201180632.2a93fe17 at posting.google.com...
> Hi all,
>
> after import re and string, I do that:
> >>> re.sub('( (.))',string.upper('\\2'),"I feel really stupid")
>
> and I received that:
> 'Ifeelreallystupid'
>
> I want that:
> 'IFeelReallyStupid (or even "IFeelSmart" ... but that is another story :-)
>
> Where is the mistake please ?
>
Well, you can't be all that far away, look:

>>> re.sub('( (.))',"X","I feel really stupid")
'IXeelXeallyXtupid'

So, you are definitely finding all occurrences. However, note that the
documentation for re.sub() says """repl can be a string or a function; if a
function, it is called for every non-overlapping occurrence of pattern""" .
You have accidentally supplied a string:

>>> string.upper("\\2")
'\\2'
>>>

Because this string contains a backslash (just one: the interpreter is
escaping it to give something that can be used in a program). Let's try
defining a function that works on the match object, which will have two
groups: the first will be the space, the second will be the single character
that follows it:

>>> def mtchupper(matchobj):
...  return string.upper(matchobj.group(2))
...
>>> re.sub('( (.))', mtchupper, "I feel really stupid")
'IFeelReallyStupid'
>>>

Success! Of course now you probably realise you can do the splitting in your
function and use a simpler pattern:

>>> def mtchupper(matchobj):
...  return string.upper(matchobj.group(1)[1])
...
>>> re.sub('( .)', mtchupper, "I think I understand better now")
'IThinkIUnderstandBetterNow'

Hope this helps. You seem to be getting it!

>>> def mtchlower(m):
...  return "-"+string.lower(m.group(1)[1])
...
>>> re.sub('( .)', mtchlower,
        "c.l.py Helps Those Who Help Themselves"
        )+"-ly y'rs  - steve"
--
Consulting, training, speaking: http://www.holdenweb.com/
Python Web Programming: http://pydish.holdenweb.com/pwp/








More information about the Python-list mailing list