Can not add backslash into input parameter using Python - python

I need to escape all special character and then add back slash () into input parameters using python. I have done something but it's not working. My code is below.
rname = request.POST.get('rname')
ename = re.escape(rname)
add_slash = ename + '\'
Here I need to escape all special character first and then add the \ with that string.

A backslash also needs to be escaped, like so
add_slash = ename + '\\'

**Hello Satya, **
Your Solution
Try this below code,
rname = request.POST.get('rname')
ename = (re.escape(rname)) + "\\"
add_slash = ename
More knowledge about string literal so read below link,
https://docs.python.org/2.0/ref/strings.html
I hope my answer is helpful.
If any query so c

Related

How to pass filter parameters in a URL in Python

I have below to send as URL parameter (params = para1)
para1 = (
('filter', 'local_ip: \'10.10.10.10\''),
)
I want to send a variable for the local IP taken from a for loop. But the syntax keep coming as a "message": "Invalid filter expression supplied"
Code is like below
for k in ip1:
if ip1 != None:
para1 = (
('filter', 'local_ip: k'),
# ('filter', 'local_ip: \'10.101.168.21\''), # working when its like this.
)
print(para1)
re2 = requests.get('https://api.example.com/devices/queries/devices/v1', headers=headers2, params=para1)
Can anybody help me to write the correct filtering command?
You've forgotten to escape another quote there: 'local_ip: \'k'' -> 'local_ip: \'k\''
It's useful to keep in mind that you can enclose strings in either ' or " quotes, so if you need to use ' inside your string, enclose the whole string into " to avoid messy escaping:
EDIT:
para1 = (
('filter', f"local_ip: '{k.rstrip()}'"),
)
Notice f before the string begins, and {} between which you can write any Python expression, and its value will be substituted in the string. .rstrip() function deletes all space characters (blanks, newlines) from the riht end of a string.

how to have both string placeholder surrounded with quotes inside a string in python?

i have xpath that looks like this:
"//*[#id="comments_408947"]/div[2]/div[2]/div[2]"
the comment_408947 must be wrapped up with quotes as well as the entire xpath.
i have the number 408947 as a string and need to add it after 'comments_'
com_id = '408947'
query= f("//*[#id=comments_" + """%s""" + "]/div[2]/div[2]/div[2]", com_id)
but it's not working.
Use triple quotes, it will solve the issue for you or you need to escape the inner ", otherwise it is interpreted as a string endpoint.,
'''//*[#id="comments_408947"]/div[2]/div[2]/div[2]'''
"//*[#id="comments_408947"]/div[2]/div[2]/div[2]" is invalid - you need to use different quotes to allow " as inside characters - or you need to escape them:
'''"//*[#id="comments_408947"]/div[2]/div[2]/div[2]"''' # works - uses ''' as delim
# too complex for string coloring here on SO but works:
""""//*[#id="comments_408947"]/div[2]/div[2]/div[2]"""" # works - uses """ as delim
"//*[#id=\"comments_408947\"]/div[2]/div[2]/div[2]" # works - escapes "
'//*[#id=\"comments_408947\"]/div[2]/div[2]/div[2]' # works - uses ' as delim
the same goes for your id-insertion -you can use string interpolation:
com_id = '408947'
query= f'''//*[#id="comments_{com_id}"]/div[2]/div[2]/div[2]''', com_id)

I want to replace a special character with a space

Here is the code i have until now :
dex = tree.xpath('//div[#class="cd-timeline-topic"]/text()')
names = filter(lambda n: n.strip(), dex)
table = str.maketrans(dict.fromkeys('?:,'))
for index, name in enumerate(dex, start = 0):
print('{}.{}'.format(index, name.strip().translate(table)))
The problem is that the output will print also strings with one special character "My name is/Richard". So what i need it's to replace that special character with a space and in the end the printing output will be "My name is Richard". Can anyone help me ?
Thanks!
Your call to dict.fromkeys() does not include the character / in its argument.
If you want to map all the special characters to None, just passing your list of special chars to dict.fromkeys() should be enough. If you want to replace them with a space, you could then iterate over the dict and set the value to for each key.
For example:
special_chars = "?:/"
special_char_dict = dict.fromkeys(special_chars)
for k in special_char_dict:
special_char_dict[k] = " "
You can do this by extending your translation table:
dex = ["My Name is/Richard????::,"]
table = str.maketrans({'?':None,':':None,',':None,'/':' '})
for index, name in enumerate(dex, start = 0):
print('{}.{}'.format(index, name.strip().translate(table)))
OUTPUT
0.My Name is Richard
You want to replace most special characters with None BUT forward slash with a space. You could use a different method to replace forward slashes as the other answers here do, or you could extend your translation table as above, mapping all the other special characters to None and forward slash to space. With this you could have a whole bunch of different replacements happen for different characters.
Alternatively you could use re.sub function following way:
import re
s = 'Te/st st?ri:ng,'
out = re.sub(r'\?|:|,|/',lambda x:' ' if x.group(0)=='/' else '',s)
print(out) #Te st string
Arguments meaning of re.sub is as follows: first one is pattern - it informs re.sub which substring to replace, ? needs to be escaped as otherwise it has special meaning there, | means: or, so re.sub will look for ? or : or , or /. Second argument is function which return character to be used in place of original substring: space for / and empty str for anything else. Third argument is string to be changed.
>>> a = "My name is/Richard"
>>> a.replace('/', ' ')
'My name is Richard'
To replace any character or sequence of characters from the string, you need to use `.replace()' method. So the solution to your answer is:
name.replace("/", " ")
here you can find details

Delete CHOOSEN special character function

please help cause Im loosing my mind. I can find similar problems but none of them is that specific.
-Im trying to create a simple compilator in Tkinter, with the function to delete a choosen special character.
-I got the buttons for each character (dot, colon, etc.), and I want to create a function that would take a special character as an argument, then delete it from the ScrolledText field. Here is my best try:
import re
content = 'Test. test . .test'
special = '.'
def delchar(char):
adjustedchar = str("'[" + char + "]'")
p = re.compile(adjustedchar)
newcontent = p.sub('', content)
print(newcontent)
delchar(special)
output (nothing has changed)>>> 'Test. test . .test'
What's going on here? How to make it work? Is there a better solution?
I know that I could create each function for each character (tried, and it's working), but that would create a 10 uneccesary functions. I want to keep it DRY. Also, my next function is gonna do the same thing, just using the user-input.
What doesn't work is that argument. If I would print eg. adjustedchar, I'd get:
'[.]'
It's a format that re.compile() should accept, right?
Your code works the problem is that . (a dot) is a special character.
Change your code to:
import re
content = 'Test. test . .test'
special = '\.'
def delchar(char):
adjustedchar = str("'[" + char + "]'")
p = re.compile(char)
newcontent = p.sub('', content)
print(newcontent)
delchar(special)
You can also check by making special = 't'. In your function you can do checks for the special characters.
You need to re.compile with the pattern you want to match, not with the replace-content:
import re
content = 'Test. test . .test'
special = '.'
def delchar(char):
adjustedchar = str("'[" + char + "]'")
p = re.compile("["+char+"]") # replace the dots, not '.'
newcontent = p.sub(adjustedchar, content) # with adjustedchar,change to '' if you like
print(newcontent)
delchar(special)
Your content does not contain '.' so it does not replace. If you change the pattern to "[.]" you are looking for literal dots to be replaced - not dots flanked by '
Output:
Test'[.]' test '[.]' '[.]'test
You could as well just use string replace: Test. Test . .test'.replace(".","'.'")

tips needed to write the function quote this

Write a function called "quote_this" that accepts two
arguments: a string representing a quote (not surrounded
by quotation marks) and a string of a name. The function
should return a new string with the quote surrounded by
quotation marks (") followed by a dash and the given
name in python.
don't know how to go about starting to solve this.any help
This should work:
def quote_this(quote,name):
return '"' + quote + '" - ' + name
In which quote represents the string of your quote and name the name of the author
def quote_this(quote_string, name):
return '\"' + str(quote_string) + '\"' + ' - ' + str(name)
quote_this('this', 'John')
You should really look into Google or read a book for this. It's really simple. Also, provide a sample code next time.

Categories

Resources