Why is it different from the example on the tutorial?

Rustom Mody rustompmody at gmail.com
Sun Jul 6 18:01:39 CEST 2014


On Sunday, July 6, 2014 5:43:55 PM UTC+5:30, rxj... at gmail.com wrote:
> Hi,

> I type the following sample codes on Python, but it echoes differently.

> Regular expressions are compiled into pattern objects, which have methods for
> various operations such as searching for pattern matches or performing string
> substitutions.

> >>> import re
> >>> p = re.compile('ab*')
> >>> p  

> What I get on Python console:

> $ python
> Python 2.7.5 (default, Oct  2 2013, 22:34:09)
> [GCC 4.8.1] on cygwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import re
> >>> p = re.compile('ab*')
>   File "<stdin>", line 1
>     p = re.compile('ab*')
>     ^
> SyntaxError: invalid syntax

1. For *using* regular exps match is fine
For *hacking in the interpreter* I find findall more convenient.
match and findall take the same arguments

2. I wouldn't bother with compile at least at the start
3. Use raw strings for patterns even if it does not seem necessary (below)

$ python
Python 2.7.7 (default, Jun  3 2014, 16:16:56) 
[GCC 4.8.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from re import findall

>>> findall(r'ab*', 'abcd')
['ab']
>>> findall(r'ab*', 'abcdab')
['ab', 'ab']
>>> findall(r'ab*', 'abcdabbb')
['ab', 'abbb']




More information about the Python-list mailing list