[Tutor] regular expressions
Monika Jisswel
monjissvel at googlemail.com
Tue Aug 5 13:57:23 CEST 2008
here is what my interpreter gives :
>>>
>>>
>>> text = "Bill Smith is nice"
>>> print text
Bill Smith is nice
>>> re.sub('Smith', '', text)
'Bill is nice'
>>> text = "Jim likes a girl (Susan)"
>>> print text
Jim likes a girl (Susan)
>>>
KeyboardInterrupt
>>> re.sub('(Susan)', '', text)
'Jim likes a girl ()'
>>> re.sub(r'(Susan)', '', text)
'Jim likes a girl ()'
>>> re.sub(r'\(Susan\)', '', text)
'Jim likes a girl '
>>>
>>> re.sub('a', 'aa', 'I am a girl')
'I aam aa girl'
>>>
so your code seems to be working you just maybe don't know about the 'r'
which mean raw & which tells python to take the special characters as they
are without interpreting them. some special characters are : \n (new line),
\b (space), \t (tab); \r (cariage return on windows).
2008/8/5 Jim Morcombe <jmorcombe at westnet.com.au>
> Could someone please give me some help using the "re" module.
>
> This works:
> --------------------------------
> import re
>
> text = "Jim is a good guy"
>
> s2 = re.sub('Jim', 'Fred', text)
> print s2
>
> and I get "Fred is a good guy"
> ---------------------------------
> If I have:
> text = "Bill Smith is nice"
> how do I get rid of "Smith" and just have
> "Bill is nice"
>
> I tried
> s2 = re.sub('Smith', '', text)
> but it complained.
>
> If I have:
> text = "Jim likes a girl (Susan)"
> and I want to get rid of "(Susan)", how do I do this.
>
> First, the "(" seems to muck things up.
> Second, how do I just use "re" to delete characters. I tried using "sub",
> but it doesn't seem to like
>
> Jim Morcombe
>
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080805/e985f08d/attachment.htm>
More information about the Tutor
mailing list