Python re expr from Perl to Python
Paddy
paddy3118 at netscape.net
Sat Jan 6 12:07:38 EST 2007
More information about the Python-list mailing list
Sat Jan 6 12:07:38 EST 2007
- Previous message (by thread): Python re expr from Perl to Python
- Next message (by thread): Python re expr from Perl to Python
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Michael M. wrote:
> In Perl, it was:
>
>
> ## Example: "Abc | def | ghi | jkl"
> ## -> "Abc ghi jkl"
> ## Take only the text betewwn the 2nd pipe (=cut the text in the 1st
> pipe).
> $na =~ s/\ \|(.*?)\ \|(.*?)\ \|/$2/g;
>
> ## -- remove [ and ] in text
> $na =~ s/\[//g;
> $na =~ s/\]//g;
> # print "DEB: \"$na\"\n";
>
>
> # input string
> na="Abc | def | ghi | jkl [gugu]"
> # output
> na="Abc ghi jkl gugu"
>
>
> How is it done in Python?
Here is how to do it without regexps in python.
The first and last line below are all that are needed. The others show
intermediate expressions that lead to the result.
>>> from itertools import groupby
>>> na="Abc | def | ghi | jkl [gugu]"
>>> [(g[0], ''.join(g[1])) for g in groupby(na, lambda c: c not in ' \t|[]')]
[(True, 'Abc'), (False, ' | '), (True, 'def'), (False, ' | '), (True,
'ghi'), (False, ' | '), (True, 'jkl'), (False, ' ['), (True, 'gugu'),
(False, ']')]
>>> [''.join(g[1]) for g in groupby(na, lambda c: c not in ' \t|[]') if g[0]]
['Abc', 'def', 'ghi', 'jkl', 'gugu']
>>> ' '.join(''.join(g[1]) for g in groupby(na, lambda c: c not in ' \t|[]') if g[0])
'Abc def ghi jkl gugu'
>>>
- Paddy.
- Previous message (by thread): Python re expr from Perl to Python
- Next message (by thread): Python re expr from Perl to Python
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list