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

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(",'"))
",'"

Related

In Python if you return a string,it will be displayed with quotes around it but If you print the string, it will not be shown with quotes. why? [duplicate]

This question already has answers here:
In the Python interpreter, how do you return a value without single quotes around it?
(2 answers)
Closed 3 years ago.
In the Python interactive prompt, if you return a string, it will be displayed with quotes around it. But if you just print the string, it will not be shown with quotes. Why?
>>> a='world'
>>> a
'world'
>>> print(a)
world
Simply put:
The quotes allow python to treat whatever is inside of them as a 'string literal'; that way, if we wanted to write a string like 'print([0, 1, 2])' we would actually literally get print([0, 1, 2]) as a reply instead of [0, 1, 2]. The print function in python only prints the string literal out to the console for the user to see, since the user knows this is a string.
If we wanted to include quotes in the print, we could use a mixture of ' and " (single vs. double) quotes. For example, we could 'define' the string literal / tell python its going to be a literal with outer quotes "" then inside of that put 'testing...'. So if we set that equal to a variable for clarity (example = "'testing...'") now print(example), as you can see we would get the single quotes (') included in the output.
return function holds the value of the string and that value is the string.
print function doesn't hold the value, it removes the string quotes leading and trailing then displays the value on the screen.
as for example,
check the (strip function) of python, it helps to remove leading and trailing values

Properly Escaping String 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")

python string good practise: ' vs " [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Single quotes vs. double quotes in Python
I have seen that when i have to work with string in Python both of the following sintax are accepted:
mystring1 = "here is my string 1"
mystring2 = 'here is my string 2'
Is anyway there any difference?
Is it by any reason better use one solution rather than the other?
Cheers,
No, there isn't. When the string contains a single quote, it's easier to enclose it in double quotes, and vice versa. Other than this, my advice would be to pick a style and stick to it.
Another useful type of string literals are triple-quoted strings that can span multiple lines:
s = """string literal...
...continues on second line...
...and ends here"""
Again, it's up to you whether to use single or double quotes for this.
Lastly, I'd like to mention "raw string literals". These are enclosed in r"..." or r'...' and prevent escape sequences (such as \n) from being parsed as such. Among other things, raw string literals are very handy for specifying regular expressions.
Read more about Python string literals here.
While it's true that there is no difference between one and the other, I encountered a lot of the following behavior in the opensource community:
" for text that is supposed to be read (email, feeback, execption, etc)
' for data text (key dict, function arguments, etc)
triple " for any docstring or text that includes " and '
No. A matter of style only. Just be consistent.
I tend to using " simply because that's what most other programming languages use.
So, habit, really.
There's no difference.
What's better is arguable. I use "..." for text strings and '...' for characters, because that's consistent with other languages and may save you some keypresses when porting to/from different language. For regexps and SQL queries, I always use r'''...''', because they frequently end up containing backslashes and both types of quotes.
Python is all about the least amount of code to get the most effect. The shorter the better. And ' is, in a way, one dot shorter than " which is why I prefer it. :)
As everyone's pointed out, they're functionally identical. However, PEP 257 (Docstring Conventions) suggests always using """ around docstrings just for the purposes of consistency. No one's likely to yell at you or think poorly of you if you don't, but there it is.

Difference between using ' and "? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Difference between the use of double quote and quotes in python
Single quotes vs. double quotes in Python
So I am now learning python, and was creating a function. What is the difference between using ' and ". I will create a sample function below to exemplify my question.
def question(variable):
print variable
now what is the difference between calling
question("hello")
and
question('hello')
they both print hello, but why can I use both? Is it just because python is flexible? I was confused because ' is usually used for chars where as " is for strings for java right?
Both are equal and what you use is entirely your preference.
As far as the char vs string thing is concerned, refer to the Zen of Python, (PEP 20 or import this)
Special cases aren't special enough to break the rules.
A string of length 1 is not special enough to have a dedicated char type.
Note that you can do:
>>> print 'Double" quote inside single'
Double" quote inside single
>>> print "Single' quote inside double"
Single' quote inside double
" is useful when you have ' into the string and vice versa
Python does not have that restriction of single quotes for chars and double quotes for strings.
As you can see here the grammar explicitly allows both for strings.
http://docs.python.org/reference/lexical_analysis.html#string-literals

Python Command Line "characters" returns 'characters'

Thanks in advance for your help.
When entering "example" at the command line, Python returns 'example'. I can not find anything on the web to explain this. All reference materials speaks to strings in the context of the print command, and I get all of the material about using double quotes, singles quotes, triple quotes, escape commands, etc.
I can not, however, find anything explaining why entering text surrounded by double quotes at the command line always returns the same text surrounded by single quotes. What gives? Thanks.
In Python both 'string' and "string" are used to represent string literals. It's not like Java where single and double quotes represent different data types to the compiler.
The interpreter evaluates each line you enter and displays this value to you. In both cases the interpreter is evaluating what you enter, getting a string, and displaying this value. The default way of displaying strings is in single quotes so both times the string is displayed enclosed in single quotes.
It does seem odd - in that it breaks Python's rule of There should be one - and preferably only one - obvious way to do it - but I think disallowing one of the options would have been worse.
You can also enter a string literal using triple quotes:
>>> """characters
... and
... newlines"""
'characters\nand\nnewlines'
You can use the command line to confirm that these are the same thing:
>>> type("characters")
<type 'str'>
>>> type('characters')
<type 'str'>
>>> "characters" == 'characters'
True
The interpreter uses the __repr__ method of an object to get the display to print to you. So on your own objects you can determine how they are displayed in the interpreter. We can't change the __repr__ method for built in types, but we can customise the interpreter output using sys.displayhook:
>>> import sys
>>> def customoutput(value):
... if isinstance(value,str):
... print '"%s"' % value
... else:
... sys.__displayhook__(value)
...
>>> sys.displayhook = customoutput
>>> 'string'
"string"
In python, single quotes and double quotes are semantically the same.
It struck me as strange at first, since in C++ and other strongly-typed languages single quotes are a char and doubles are a string.
Just get used to the fact that python doesn't care about types, and so there's no special syntax for marking a string vs. a character. Don't let it cloud your perception of a great language
Don't get confused.
In python single quotes and double quotes are same. The creates an string object.

Categories

Resources