473,385 Members | 1,464 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Most direct way to strip unoprintable characters out of a string?

When sanitizing data coming in from HTML forms, I'm doing this (lifted
from the Python Cookbook):

from string import maketrans, translate, printable
allchars = maketrans('','')
delchars = translate(allchars, allchars, printable)
input_string = translate(input_string, allchars, delchars)

Which is OK. But it seems like there should be more straightforward way
that I just haven't figured out. Is there?

Thanks,
Steve Bergman
Sep 24 '05 #1
6 1849
"Steve Bergman" <st***@rueb.com> wrote:
When sanitizing data coming in from HTML forms, I'm doing this (lifted
from the Python Cookbook):

from string import maketrans, translate, printable
allchars = maketrans('','')
delchars = translate(allchars, allchars, printable)
input_string = translate(input_string, allchars, delchars)

Which is OK. But it seems like there should be more straightforward way
that I just haven't figured out. Is there?


If by straightforward you mean one-liner, there is:
''.join(c for c in input_string if c not in string.printable)

If you care about performance though, string.translate is faster; as always, the best way to decide
on a performance issue is to profile the alternatives on your data and see if it's worth going for
the fastest one at the expense of readability.

George
Sep 24 '05 #2
George Sakkis wrote:


If by straightforward you mean one-liner, there is:
''.join(c for c in input_string if c not in string.printable)

If you care about performance though, string.translate is faster; as always, the best way to decide
on a performance issue is to profile the alternatives on your data and see if it's worth going for
the fastest one at the expense of readability.

Thank you for the reply. I was really thinking of some function in the
standard library like:

s = stripUnprintable(s)

When I learned php, I more or less took the route of using whatever I
found that 'worked'. In learning Python, I'm trying to take my time and
learn the 'right' (that's pronounced 'beautiful') way of doing things.

As it stands, I've stashed the string.translate code in a short function
with a comment explaining what it does and how. I mainly didn't want to
use that if there was some trivial built-in that everyone else uses.

Thanks Again,
Steve
Sep 25 '05 #3
"Steve Bergman" <st***@rueb.com> wrote:
George Sakkis wrote:


If by straightforward you mean one-liner, there is:
''.join(c for c in input_string if c not in string.printable)

If you care about performance though, string.translate is faster; as always, the best way to decideon a performance issue is to profile the alternatives on your data and see if it's worth going forthe fastest one at the expense of readability.

Thank you for the reply. I was really thinking of some function in the
standard library like:

s = stripUnprintable(s)

When I learned php, I more or less took the route of using whatever I
found that 'worked'. In learning Python, I'm trying to take my time and
learn the 'right' (that's pronounced 'beautiful') way of doing things.

As it stands, I've stashed the string.translate code in a short function
with a comment explaining what it does and how. I mainly didn't want to
use that if there was some trivial built-in that everyone else uses.


No there's not a stripUnprintable in a standard module AFAIK, and that's a good thing; if every
little function that one might ever wanted made it to the standard library, the language would be
overwhelming.

Make sure you calculate the unprintable characters only the first time it is called, not every time.
Here's a way to encapsulate this in the same function, without polluting the global namespace with
allchars and delchars:

import string

def stripUnprintable(input_string):
try: filterUnprintable = stripUnprintable.filter
except AttributeError: # only the first time it is called
allchars = string.maketrans('','')
delchars = allchars.translate(allchars, string.printable)
filterUnprintable = stripUnprintable.filter = lambda input: input.translate(allchars,
delchars)
return filterUnprintable(input_string)

George
Sep 25 '05 #4
George Sakkis wrote:
No there's not a stripUnprintable in a standard module AFAIK, and
that's a good thing; if every little function that one might ever wanted
made it to the standard library, the language would be overwhelming.


....and if there was a stripUnprintable function in the standard library that
was based on C's mostly brain-dead locale model, US programmers
would produce even more web applications that just don't work for non-
US users...

("sanitizing" HTML data by running filters over encoded 8-bit data is hardly
ever the right thing to do...)

</F>

Sep 25 '05 #5
Fredrik Lundh wrote:
("sanitizing" HTML data by running filters over encoded 8-bit data is hardly
ever the right thing to do...)

I'm very much open to suggestions as to the right way to do this. I'm
working on this primarily as a learning project and security is my
motivation for wanting to strip the unprintables.

Is there a better way? (This is a mod_python app , just for reference.)

Thanks,
Steve
Sep 25 '05 #6
Steve Bergman wrote:
Fredrik Lundh wrote:
("sanitizing" HTML data by running filters over encoded 8-bit data is
hardly
ever the right thing to do...)

I'm very much open to suggestions as to the right way to do this. I'm
working on this primarily as a learning project and security is my
motivation for wanting to strip the unprintables.

Is there a better way? (This is a mod_python app , just for reference.)


Deal with encodings properly. That characters are "unprintable" means
that you have an encoding mismatch - your output device (usually a
terminal, but a browser is a sort of device too) can't make sense of
certain byte codes - and pukes on you. But these bytecode come from
somewhere, and aren't "random".

So I suggest you read upon the subjects of unicode, encodings - and this
in the context of python, of course :)

BTW: if that HTML was XHTML, it weren't valid if the contents didn't
match the specified encoding in the header - which doesn't mean that
sometimes these mismatch because of misunderstandings on the programmer
side.

Diez
Sep 26 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Giampiero Gabbiani | last post by:
Hi to all, Is there a simple way to implement a strip algorithm on std::string using STL? I'm sure that it's possible to implement it using some transform, but my knowledge of STL is POOR. ...
6
by: Mark C | last post by:
All, Is there such a function that can strip all non alpha ( not between a-z) characters from a string? I have a function that I currently use that will strip one character at a time from a...
5
by: dan.j.weber | last post by:
I'm using Python 2.3.5 and when I type the following in the interactive prompt I see that strip() is not working as advertised: >>>s = 'p p:p' >>>s.strip(' :') 'p p:p' Is this just me or...
2
by: ImageAnalyst | last post by:
Tom, Nikolay: That code doesn't work, at least not in VS2005. What happens is that when you replace with VBNullChar, it basically chops off the string from that point onwards. So Sna?*|fu" would...
6
by: eight02645999 | last post by:
hi can someone explain strip() for these : 'example' when i did this: 'abcd,words.words'
3
by: Drum2001 | last post by:
Hello, I have a textbox "Fname" where users input what they would like a filename to be. I would like to strip out all invalid characters with an "After Update" Event. I have searched other...
3
by: Colin J. Williams | last post by:
The Library Reference has strip( ) Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed....
0
by: =?iso-8859-1?q?C=E9dric_Lucantis?= | last post by:
Hi, I don't see any string method to do that, but you can use a regexp : 'exaple' -- Cédric Lucantis
4
by: Poppy | last post by:
I'm using versions 2.5.2 and 2.5.1 of python and have encountered a potential bug. Not sure if I'm misunderstanding the usage of the strip function but here's my example. var = "detail.xml"...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.