Re: [Tutor] string.unprintable?

Magnus Lycka magnus at thinkware.se
Mon Nov 24 17:08:41 EST 2003


Clay Shirky <clay at ernie.webservepro.com> wrote:
> if not string.printable in line
> 
> for some reason matches everything in the file, even though I've .strip()ed
> the line aready.

Of course! string.printable is just a string with all the
printable characters. "if not string.printable in line:" means
"If the content of string.printable is not a substring of the
string referred to as 'line'."

>>> import string
>>> print string.printable
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-/:;<=>?@[\]^_`{|}~
&#9794;&#9792;
>>> string.printable in "Hello"
False
>>> string.printable not in "Hello"
True
>>>

I think you want something like "If all of the characters in the
line are in string.printable I want to print the line". That seems
to require a loop...

One version would be this:

>>> def printIfPrintable(line):
..     ok = True
..     for char in line:
..             if char not in string.printable:
..                     ok = False
..     if ok:
..             print line
..
>>> printIfPrintable('Hello there')
Hello there
>>> printIfPrintable('Hello there\0x0f')
>>>

Here's a shorter version using reduce and list comprehension.

>>> def printIfPrintable(line):
..     import operator
..     if reduce(operator.mul, [(x in string.printable) for x in line]):
..             print line
..
>>> printIfPrintable('Hello there')
Hello there
>>> printIfPrintable('Hello there\0x0f')
>>>

Without reduce:

>>> def printIfPrintable(line):
..     if [x for x in line if x in string.printable]==list(line):
..             print line
..
>>> printIfPrintable('Hello there\0x0f')
>>> printIfPrintable('Hello there')
Hello there
>>>

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus at thinkware.se



More information about the Tutor mailing list