Difference between using ' and "? [duplicate] - python

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

Related

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 do I put a string and a variable in the same print? [duplicate]

This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 3 years ago.
I'm coding a little game and I want a score system. I have two variables that I want to display as "The current score is: X/X" but its not including the variables
I've tried putting it in 'quotes' put it didn't work
U = 2
L = 3
print("Current score: U/L")
I want it to be "Current score: 2/3"
print(f"Current score: {U}/{L}")
Strings enclosed with simple quotes or double-quotes imply that all characters in it are just literal text - they are not interpreted as variables.
From Python 3.6, the prefix f for the quotes delimiting the string denotes an special literal which can include Python expressions inside - including variables. Still, to separate these variables from plain text (and avoid unpredictable substitutions), these expressions have to be further delimited by { }, inside the string.
Prior to Python 3.6, one would have to do it in two separate steps: create a plain string with special markers were the variables contents would be inserted, and then call the .format method on the string. (or, there is an older method using the % operator instead). Fully documenting these other methods would be long - but a short form would require one to write:
print("Current score: {}/{}".format(U, L))

How to write a string starting with ' and ending with " in Python? [duplicate]

This question already has answers here:
Having both single and double quotation in a Python string
(9 answers)
Closed 5 years ago.
I'd like to save the following characters 'bar" as a string variable, but it seems to be more complicated than I thought :
foo = 'bar" is not a valid string.
foo = ''bar"' is not a valid string either.
foo = '''bar"'' is still not valid.
foo = ''''bar"''' actually saves '\'bar"'
What is the proper syntax in this case?
The last string saves '\'bar"' as the representation, but it is the string you're looking for, just print it:
foo = ''''bar"'''
print(foo)
'bar"
when you hit enter in the interactive interpreter you'll get it's repr which escapes the second ' to create the string.
Using a triple quoted literal is the only way to define this without explicitly using escapes. You can get the same result by escaping quotes:
print('\'foo"')
'foo"
print("'foo\"")
'foo"

Why does python use both " " and ' ' to make a string literal [duplicate]

This question already has answers here:
Single quotes vs. double quotes in Python [closed]
(19 answers)
Closed 9 years ago.
Python's Philosophy:
....
Simple is better than complex.
....
So why does it use both double quote " " and single quote ' ' to indicate something is a string literal.
I was lost when I typed:
x = "aa"
x
And saw:
'aa'
But not:
"aa"
When I saw the above philosophy, I doubted it. It needs some explanations.
This isn't complex at all. In fact, it's rather helpful.
Both '' and "" can be used in python. There's no difference, it's up to you.
In your example, when you type x, you are given the representation of the string (i.e, it's equivalent to print repr(x)). It wouldn't have mattered if you did x = 'aa'
I like to use either for cases such as:
print 'Bill said, "Hey!"'
print "I'm coming!"
If we used " for the first example, then there would be an error because Python would interpret it as "Bill said, ".
If we used ' for the second example, then there would be an error because Python would interpret it as 'I'
Of course, you could just escape the apostrophes, but beautiful is better than ugly.
You can use "" to be able to write "I'm legend" for example.

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.

Categories

Resources