Wednesday, 16 January 2013

Input Sanitization


Input Sanitization

Often you need to normalize the user’s input so that all input is either in
lower or upper case. Functions upper() and lower() do the job:
a = "PyTHon"
print a.upper()
print a.lower()
The print statements output ‘PYTHON’ and then ‘python’.
If you need to be sure that a string does not contain any leading
or trailing white space, use the strip() function. The following code
outputs the string ‘fancy message’:
a = " fancy message "
print a.strip()
This is actually one of the most often needed operations for strings – in
this book it is used in 12 examples. It is especially useful when you
receive data from a file or over a network connection.
You can replace a substring in a string with the function replace().
The following example outputs ‘Python is the future’:
a = "Java is the future"
print a.replace("Java", "Python")
You can also replace individual characters in a string, which is often
useful for cleaning up input, say, from a web service. The following
example removes all spaces in a string and outputs ‘1,2,3,4,5,6’.
a = " 1, 2, 3, 4, 5,6 "
print a.replace(" ", "")
If you need to cut a string into a list of substrings, use the function
split(). In default mode, split() cuts the string at every space
character. If you give a string parameter to split(), it is used as the
delimiter instead. The following example prints out the list ["one",
"two", "three", "four"].
txt = "one:two:three:four"
print txt.split(":")

No comments:

Post a Comment