perl to python code [A-Za-z0-9]

Ben Hutchings ben.hutchings at roundpoint.com
Wed May 9 16:29:03 EDT 2001


"DON WAGNER" <wagnertuba at hotmail.com> writes:

> Hello,
> I'm an inexperienced programmer. I've written some code in perl that
> counts characters a-zA-Z0-9.
>
> $_=<INFILE>;
> $words=split(/\s/,$_);
> $chars=tr/A-Za-z0-9//;
> print("chars:$chars\n");
> print("words: $words\n");
>
> I'm wondering how to use the python character matching set [A-Za-z0-9]
> to do the same task.
<snip>

This is a pretty close translation:

    import re
    line = infile.readline()
    words = len(line.split())
    _, chars = re.subn('[A-Za-z0-9]', '', line)
    print 'chars:', chars
    print 'words:', words

However, I'm unsure whether Python's string split method works
in exactly the same way as Perl's split function.  You should
compare their behaviour when the input line has leading and/or
trailing space.

-- 
Any opinions expressed are my own and not necessarily those of Roundpoint.



More information about the Python-list mailing list