Entry
I'd like to know if PYTHON can count words and characters , not including spaces, as easily as PERL. ex. $words=split(/\s/,$_), $chars=tr/A-Za-z0-9//;
Mar 26th, 2002 10:44
Michael Chermside, don wagner,
Yes.
>>> s = 'This has eight words and 47 non-whitespace characters.'
>>> len( s.split() ) # words
8
>>> len( ''.join( s.split() ) ) # characters
47
But the Perl that you wrote only counts letters and digits, not
characters. Python can do that also if it's what you prefer... I'll
attempt to mimic your Perl by using a regular expression:
>>> len( [c for c in s if re.match('[A-Za-z0-9]', c)] )
45