Properly Escaping String Python - python

I'm trying to use selenium to locate a checkbox within an unordered list:
ul=browser.find_element_by_xpath('//[#id="TestTake"]/div[2]/div/div/ol/li[{}]/div[2]/ul'.format(num))
checkbox_id=ul.find_element_by_xpath("//[contains(text(),'{}')]".format(correct.replace("'","\'"))).get_attribute("for")
The problem with:
"//[contains(text(),'{}')]".format(correct.replace("'","\'"))).get_attribute("for"
occurs when correct is equal to L' or something that contains a quote.
How can I properly escape the single quote? I'm not sure if the correct will have a quote or not, so I need to be able to handle both cases, a double quote as well.
Also, this is the only approach because I only can get the id by the attribute for which I find by using its contents.

Turns out that string concatenation did the trick:
checkbox_id = ul.find_element_by_xpath("//*[contains(text(),\"" + correct + "\")]").get_attribute("for")

Related

How to Write code as text in python? or how to use multiple quotations in one string?

I'm trying to fix my code in c# with python with the replace element. So this is what I type
Sentence = "{My c# code}"
print(Sentence.replace("Console","System.Console"))
Because I want to add "System" behind all the Consoles but theres to many to do it manually. but the problem is pycharm thinks is all real code and not string value therefore unable to replace the words. Any help?
use triple quotes you can use single or double quotes
Sentence = """{My c# code}"""

pywinauto escaping special characters

I am using type_keys() on a combobox to upload files via a file dialog. As mentioned in similar SO posts, this function omits certain special characters in the text that it actually types into the combobox. I'm resolving this by simply replacing every "specialchar" in that string with "{specialchar}". So far I've found the need to replace the following chars: + ^ % ( ).
I'm wondering where I can find the complete list of characters that require this treatment. I don't think it's this list because I'm not seeing, for example, the % symbol there. I also tried checking keyboard.py from the keyboard library but I don't know if it can be found there.
PS. I realize that instead of using type_keys(), for example, using send_keys() or set_edit_text(), the escaping of special characters might be done for me automatically. However, for various reasons, it looks like type_keys() works the best for my particular file dialog/situation.
Thanks
This is the full documentation: https://pywinauto.readthedocs.io/en/latest/code/pywinauto.keyboard.html All special characters can be wrapped by {}

How to use repr() instead of backquotes in Python 3 [duplicate]

This question already has answers here:
Having both single and double quotation in a Python string
(9 answers)
Closed 3 years ago.
I'm looking for a way to declare a string that contains double quotes and single quote.
In javascript I would do
let str = `"," '`
But when I try the same syntax in python, my IDE shows this error
Python version 3.7 does not support backquotes, use repr() instead
How can I use repr() to achieve this result?
The reason the error message says what it does is because backquotes have never been used in Python to do what you want. Instead, they used to be a shortcut for using the repr function, that is no longer supported.
According to documentation it take an object
Everything is an object in Python, so there is no issue there. But there is an issue in that the repr function does not do what you want.
We need to go back to the original question instead:
I'm looking for a way to declare a string that contains double quotes and single quote.
In Python, you may either escape whichever quote is the one you used for the string, for example:
"\",\" '" # using double quotes
'"," \'' # using single quotes
Or you may use so-called triple quotes:
""""," '""" # like so
But beware that this does not work if you have the same kind of quote at the end of the string:
# '''"," '''' -- does not work!
'''"," \'''' # works, but it defeats the purpose
In each case, '"," \'' is the form that Python will use to report the string back to you.
The message in the IDE is referring to using backticks around a variable name or other expression. In Python 2, `someVar` was a shortcut for repr(someVar).
But this isn't really what you're trying to do. The message is simply hard-coded for any use of backticks.
You just have to escape the quotes that are the same as the string delimiter.
s = '"," \''
I figured that out
So literally all I had to do was this
text = repr(",'") # returns this string ",'"
The part that confused me was I wasn't sure how to pass the argument to the function since according to documentation I should have passed an object, not a string or a list of string. Until I realized that a string is an object too
A few examples that helped me to understand it in details
>>> print("123")
123
>>> print(repr("123"))
'123'
>>> print(repr(",'"))
",'"

how to pass a string to to an xpath?

I have an xpath in the following format
xpath='//*[#id="peoplegrid"]/div[5]/div[1]/a'
I want to pass a string to the first div in the x path in the following manner
x=[1,2,3,4,5]
for i in x:
xpath='//*[#id="peoplegrid"]/div[',+str(i),']/div[1]/a'
print(xpath)
However when I run this, it states that bad operand type for unary +: 'str'
How can I pass a string to this xpath
Following is the full piece of code I am working on
x=[1,2,3,4]
for i in x:
python_button=driver.find_element_by_xpath('//*[#id="peoplegrid"]/div,'+[str(x)]+'/div[1]/a')
python_button.click()
driver.execute_script("window.history.go(-1)")
You're missing the second +. Try something like this.
xpath='//*[#id="peoplegrid"]/div['+str(i)+']/div[1]/a'
I cannot update #Steven's answer with such a subtle (less than 6 character) change, so I've created my own answer.
What you need is the following:
xpath='//*[#id="peoplegrid"]/div['+str(i)+']/div[1]/a'
As you can tell, between my answer and #Steven's answer, mine does not include the commas within the first div portion of the XPATH. For your purposes, it is unnecessary and invalid to place the commas in the string. Commas are typically used in print statements to prevent newlines from being appended to the output.
EDIT: In regards to the change to the original post and the comments therein, concatenating a list to a string is also invalid. Merely use an interpreter and try compiling the code, and a TypeError: must be str, not list will be thrown. This makes sense, since you cannot append a list directly to a str; however, if the contents of the list are strings, or can be converted to strings, then you can concatenate these. See here for an explanation of string concatentation in Python.
It's best to avoid constructing the XPath expression by string concatenation. Disadvantages:
(a) you need to worry about escaping strings that contain special characters
(b) you need to REALLY worry about it if there's any possibility of people inserting bad strings maliciously (XPath injection attacks)
(c) you have to compile the expression each time it's used.
I don't know the Python API you are using, but most XPath APIs allow you to compile an expression containing variables (eg. '//[#id="peoplegrid"]/div[$param]/div[1]/a') and then bind a value to the variable separately. If you can do this then it's much preferable and avoids the above disadvantages.

[Python]How to deal with a string ending with one backslash?

I'm getting some content from Twitter API, and I have a little problem, indeed I sometimes get a tweet ending with only one backslash.
More precisely, I'm using simplejson to parse Twitter stream.
How can I escape this backslash ?
From what I have read, such raw string shouldn't exist ...
Even if I add one backslash (with two in fact) I still get an error as I suspected (since I have a odd number of backslashes)
Any idea ?
I can just forget about these tweets too, but I'm still curious about that.
Thanks : )
Prepending the string with r (stands for "raw") will escape all characters inside the string. For example:
print r'\b\n\\'
will output
\b\n\\
Have I understood the question correctly?
I guess you are looking a method similar to stripslashes in PHP. So, here you go:
Python version of PHP's stripslashes
You can try using raw strings by prepending an r (so nothing has to be escaped) to the string or re.escape().
I'm not really sure what you need considering I haven't seen the text of the response. If none of the methods you come up with on your own or get from here work, you may have to forget about those tweets.
Unless you update your question and come back with a real problem, I'm asserting that you don't have an issue except confusion.
You get the string from the Tweeter API, ergo the string does not show up in your code. “Raw strings” exist only in your code, and it is “raw strings” in code that can't end in a backslash.
Consider this:
def some_obscure_api():
"This exists in a library, so you don't know what it does"
return r"hello" + "\\" # addition just for fun
my_string = some_obscure_api()
print(my_string)
See? my_string happily ends in a backslash and your code couldn't care less.

Categories

Resources