faqts : Computers : Programming : Languages : Python : Snippets : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

24 of 26 people (92%) answered Yes
Recently 9 of 10 people (90%) answered Yes

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