Sanitize Strings with Python (Python Part 16)

This class shows you how to strip out characters from strings to prevent injection attacks, and to format the text so that yo can store clean data.

  • 00:00 Intro
  • 03:35 lower(), upper(), title()
  • 05:20 replace()
  • 07:37 strip(), lstrip(), rstrip()
  • 13:04 html.escape()
  • 19:43 Final Thoughts

sanitize-case.py

name = 'BoB'
print(name)

name = name.lower()
print(name)

name = name.upper()
print(name)

name = name.title()
print(name)

sanitize-replace.py

name = '"Bob"'
print(name)

name = name.replace('"', '---')
print(name)

sanitize-strip.py

name = '   bob  '
print(f'----{name}----')

name = name.strip()
print(f'----{name}----')

user_name = '<h1>bob</h1>'
print(user_name)

user_name = user_name.strip('<>')
print(user_name)

user_name = user_name.lstrip('h1')
print(user_name)

user_name = user_name.rstrip('h1')
print(user_name)

html-escape.py

import html

user_message = '<h1>Hello World!!!</h1><a href="http://cnn.com">Click ME</a>'

with open('sanitize.html', 'w') as file:
    file.write(user_message)
    file.write('<hr>')

sanitized_message = html.escape(user_message)

with open('sanitize.html', 'a') as file:
    file.write(sanitized_message)

Be the first to comment

Leave a Reply