0

I need some help. I need to escape some specific special character like semicolon, pipe, redirection and ampersand from input string which is got by post method using python and Django. I am explaining my code below.

if request.method == 'POST':
   rname = request.POST.get('react')

Here from the above input value I need to remove the special character. Please help me.

cezar
  • 11,616
  • 6
  • 48
  • 84

4 Answers4

0

Maybe

import string
bad_chars = "()|&"
rname = "|icha()"
rname.translate(string.maketrans("", "", ), bad_chars)

# This becomes 'icha'

This is explained in Python strip() multiple characters?

mbieren
  • 1,034
  • 8
  • 31
0

This can be accomplished with regular expressions. My approach would be:

import re

special_chars = r'[;\|>&]'
rname = request.POST.get('react')
cleaned_rname = re.sub(special_chars, '', rname)

Now if the string rname contains any of the special characters they will be removed and you'll get a new string cleaned_rname with the output.

In the variable special_chars you can specify all characters that should be removed. They are enclosed within square brackets: [].

cezar
  • 11,616
  • 6
  • 48
  • 84
0

Your question is not very clear. Please state clearly which variable to escape from which characters and what they shall become.

A snippet that may help you:

>>> 'HeRllo'.replace('R','')
Hello

Or, for a given list of characters:

>>> stringToEscape = 'He≪o'
>>> sources = ['&', ';']
>>> targets = ['', '']
>>> for source, target in zip(sources, targets):
>>>   stringToEscape = stringToEscape.replace(source, target)
>>> print stringToEscape
Hello

But maybe you are looking for a special function that already exists in Django.

Manu CJ
  • 2,629
  • 1
  • 18
  • 29
0

This uses replace method:

chars = ";>" # and so on
rname = "stuff;"

for char in chars:
    if char in rname:
        new_rname = rname.replace(char,'')
    rname = new_rname

You have to assign to a new variable because strings are immutable. Result should be:

>>print(rname)
stuff