Python - difference between 'a' and "a"? [duplicate] - python

This question already has answers here:
Single quotes vs. double quotes in Python [closed]
(19 answers)
Closed 9 years ago.
I have been always mixing these two notations, regarding them both as a string in Python.
What are the differences between them?
Under what circumstances can we only use one of them?

They're the same. The only time it ever matters is that you have to escape the delimiter character: "\"" vs '"'.
Personally, I usually use ' for strings that aren't "user-visible" and " for strings that are, but I'm not completely consistent with that and I don't think it's common practice.

No difference at all: they mean exactly the same thing. Yes, that's unusual for Python ;-)
Some programmers like to put one-character strings in single quotes, and longer strings in double quotes. Probably a habit carried over from C. Do what you like :-)
Ah: a lot more discussion here.

They are equal and depend on your preferences
but you can do this:
>>> print 'Double" quote inside single'
Double" quote inside single
>>> print "Single' quote inside double"
Single' quote inside double

They are the same, though I prefer to use 'single quotes'as they're easier to read

Related

Python f-string: replacing newline/linebreak [duplicate]

This question already has answers here:
How can I use newline '\n' in an f-string to format output?
(7 answers)
Closed last month.
First off all, sorry: I'm quite certain this might be a "duplicate" but I didn't succeed finding the right solution.
I simply want to replace all linebreaks within my sql-code for logging it to one line, but Python's f-string doesn't support backslashes, so:
# Works fine (but is useless ;))
self.logger.debug(f"Executing: {sql.replace( 'C','XXX')}")
# Results in SyntaxError:
# f-string expression part cannot include a backslash
self.logger.debug(f"Executing: {sql.replace( '\n',' ')}")
Of course there are several ways to accomplish that before the f-string, but I'd really like to keep my "log the line"-code in one line and without additional helper variables.
(Besides I think it's a quite stupid behavior: Either you can execute code within the curly brackets or you cant't...not "you can, but only without backslashes"...)
This one isn't a desired solution because of additional variables:
How to use newline '\n' in f-string to format output in Python 3.6?
General Update
The suggestion in mkrieger1s comment:
self.logger.debug("Executing %s", sql.replace('\n',' '))
Works fine for me, but as it doesn't use f-strings at all (beeing that itself good or bad ;)), I think I can leave this question open.
I found possible solutions
from os import linesep
print(f'{string_with_multiple_lines.replace(linesep, " ")}')
Best,
You can do this
newline = '\n'
self.logger.debug(f"Executing: {sql.replace( newline,' ')}")
don't use f-strings, especially for logging
assign the newline to a constant and use that, which you apparently don't want to
use an other version of expressing a newline, chr(10) for instance
(Besides I think it's a quite stupid behavior: Either you can execute code within the curly brackets or you cant't...not "you can, but only without backslashes"...)
Feel free to take a shot at fixing it, I'm pretty sure this restriction was not added because the PEP authors and feature developers wanted it to be a pain in the ass.

What is the difference, if any, between using single quote and double quote in a python dictionary? [duplicate]

This question already has answers here:
Single quotes vs. double quotes in Python [closed]
(19 answers)
Closed 4 years ago.
I declare a python dictionary like this using double quotes;
{
"Name":"John",
"Date":"2/18/1998",
"Profit":25.12
}
The same python dictionary can be written like this using single quotes;
{
'Name':'John',
'Date':'2/18/1998',
'Profit':25.12
}
What is the difference, if any, between the two? What is the best practice in python? Practical-wise, I encounter no difference so far. I'm not sure if I missed out anything.
There's no difference; ' and "can be used interchangeably. There's no inherent reason to favor one over the other unless your string has a quotation mark in it (in that case, you have to surround the string with the opposite quotation mark).
Other than that, it's just personal preference. If you come from a Java background then you might prefer double quotes for strings and single quotes for "characters" (which are really just one letter strings). But at the end of the day it's the same thing.
The differences is that when you have a string like:
''a''
It will throw a syntax-error because it contains two quotes side by side
so you need to do double quotes like:
"'a'"
And same thing doing the opposite:
""a""
Will throw an error.
'"a"'
won't throw an error
(on stack-overflow the displayed code is already doesn't look right)

Output of print("""Hello World's"s""""") in python 3.6 [duplicate]

This question already has answers here:
String concatenation without '+' operator
(6 answers)
Closed 4 years ago.
I read that anything between triple quotes inside print is treated literal so tried messing things a little bit. Now I am not able to get above statement working. I searched internet but could not find anything.
statement:
print("""Hello World's"s""""")
Output I am getting:
Hello World's"s
Expected output:
Hello World's"s""
print("""Hello World's"s""""") is seen as print("""Hello World's"s""" "") because when python find """ it automatically ends the previous string beginning with a triple double-quote.
Try this:
>>> print("a"'b')
ab
So basically your '"""Hello World's"s"""""' is just <str1>Hello World's"s</str1><str2></str2> with str2 an empty string.
Triple quoted string is usually used for doc-string.
As #zimdero pointed out Triple-double quote v.s. Double quote
You can also read https://stackoverflow.com/a/19479874/1768843
And https://www.python.org/dev/peps/pep-0257/
If you really want to get the result you want just use \" or just you can do combination with ``, .format() etc
print("Hello World's\"s\"\"")
https://repl.it/repls/ThatQuarrelsomeSupercollider
Triple quotes within a triple-quoted string must still be escaped for the same reason a single quote within a single quoted string must be escaped: The string parsing ends as soon as python sees it. As mentioned, once tokenized your string is equivalent to
"""Hello World's"s""" ""
That is, two strings which are then concatenated by the compiler. Triple quoted strings can include newlines. Your example is similar to
duke = """Thou seest we are not all alone unhappy:
This wide and universal theatre
Presents more woeful pageants than the scene
Wherein we play in."""
jaques = """All the world's a stage,
And all the men and women merely players:
They have their exits and their entrances;
And one man in his time plays many parts."""
If python was looking for the outermost triple quotes it would only have defined one string here.
Simple with ''' to not complicate things:
print('''Hello World's"s""''')
Maybe this is what you are looking for?
print("\"\"Hello World's's\"\"")
Output:
""Hello World's's""

How can I print a string using .format(), and print literal curly brackets around my replaced string [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can I print a literal “{}” characters in python string and also use .format on it?
Basically, I want to use .format(), like this:
my_string = '{{0}:{1}}'.format('hello', 'bonjour')
And have it match:
my_string = '{hello:bonjour}' #this is a string with literal curly brackets
However, the first piece of code gives me an error.
The curly brackets are important, because I'm using Python to communicate with a piece of software via text-based commands. I have no control over what kind of formatting the fosoftware expects, so it's crucial that I sort out all the formatting on my end. It uses curly brackets around strings to ensure that spaces in the strings are interpreted as single strings, rather than multiple arguments — much like you normally do with quotation marks in file paths, for example.
I'm currently using the older method:
my_string = '{%s:%s}' % ('hello', 'bonjour')
Which certainly works, but .format() seems easier to read, and when I'm sending commands with five or more variables all in one string, then readability becomes a significant issue.
Thanks!
Here is the new style:
>>> '{{{0}:{1}}}'.format('hello', 'bonjour')
'{hello:bonjour}'
But I thinking escaping is somewhat hard to read, so I prefer to switch back to the older style to avoid escaping:
>>> '{%s:%s}' % ('hello', 'bonjour')
'{hello:bonjour}'

Single quotes vs. double quotes in Python [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
According to the documentation, they're pretty much interchangeable. Is there a stylistic reason to use one over the other?
I like to use double quotes around strings that are used for interpolation or that are natural language messages, and single quotes for small symbol-like strings, but will break the rules if the strings contain quotes, or if I forget. I use triple double quotes for docstrings and raw string literals for regular expressions even if they aren't needed.
For example:
LIGHT_MESSAGES = {
'English': "There are %(number_of_lights)s lights.",
'Pirate': "Arr! Thar be %(number_of_lights)s lights."
}
def lights_message(language, number_of_lights):
"""Return a language-appropriate string reporting the light count."""
return LIGHT_MESSAGES[language] % locals()
def is_pirate(message):
"""Return True if the given message sounds piratical."""
return re.search(r"(?i)(arr|avast|yohoho)!", message) is not None
Quoting the official docs at https://docs.python.org/2.0/ref/strings.html:
In plain English: String literals can be enclosed in matching single quotes (') or double quotes (").
So there is no difference. Instead, people will tell you to choose whichever style that matches the context, and to be consistent. And I would agree - adding that it is pointless to try to come up with "conventions" for this sort of thing because you'll only end up confusing any newcomers.
I used to prefer ', especially for '''docstrings''', as I find """this creates some fluff""". Also, ' can be typed without the Shift key on my Swiss German keyboard.
I have since changed to using triple quotes for """docstrings""", to conform to PEP 257.
I'm with Will:
Double quotes for text
Single quotes for anything that behaves like an identifier
Double quoted raw string literals for regexps
Tripled double quotes for docstrings
I'll stick with that even if it means a lot of escaping.
I get the most value out of single quoted identifiers standing out because of the quotes. The rest of the practices are there just to give those single quoted identifiers some standing room.
If the string you have contains one, then you should use the other. For example, "You're able to do this", or 'He said "Hi!"'. Other than that, you should simply be as consistent as you can (within a module, within a package, within a project, within an organisation).
If your code is going to be read by people who work with C/C++ (or if you switch between those languages and Python), then using '' for single-character strings, and "" for longer strings might help ease the transition. (Likewise for following other languages where they are not interchangeable).
The Python code I've seen in the wild tends to favour " over ', but only slightly. The one exception is that """these""" are much more common than '''these''', from what I have seen.
Triple quoted comments are an interesting subtopic of this question. PEP 257 specifies triple quotes for doc strings. I did a quick check using Google Code Search and found that triple double quotes in Python are about 10x as popular as triple single quotes -- 1.3M vs 131K occurrences in the code Google indexes. So in the multi line case your code is probably going to be more familiar to people if it uses triple double quotes.
"If you're going to use apostrophes,
^
you'll definitely want to use double quotes".
^
For that simple reason, I always use double quotes on the outside. Always
Speaking of fluff, what good is streamlining your string literals with ' if you're going to have to use escape characters to represent apostrophes? Does it offend coders to read novels? I can't imagine how painful high school English class was for you!
Python uses quotes something like this:
mystringliteral1="this is a string with 'quotes'"
mystringliteral2='this is a string with "quotes"'
mystringliteral3="""this is a string with "quotes" and more 'quotes'"""
mystringliteral4='''this is a string with 'quotes' and more "quotes"'''
mystringliteral5='this is a string with \"quotes\"'
mystringliteral6='this is a string with \042quotes\042'
mystringliteral6='this is a string with \047quotes\047'
print mystringliteral1
print mystringliteral2
print mystringliteral3
print mystringliteral4
print mystringliteral5
print mystringliteral6
Which gives the following output:
this is a string with 'quotes'
this is a string with "quotes"
this is a string with "quotes" and more 'quotes'
this is a string with 'quotes' and more "quotes"
this is a string with "quotes"
this is a string with 'quotes'
I use double quotes in general, but not for any specific reason - Probably just out of habit from Java.
I guess you're also more likely to want apostrophes in an inline literal string than you are to want double quotes.
Personally I stick with one or the other. It doesn't matter. And providing your own meaning to either quote is just to confuse other people when you collaborate.
It's probably a stylistic preference more than anything. I just checked PEP 8 and didn't see any mention of single versus double quotes.
I prefer single quotes because its only one keystroke instead of two. That is, I don't have to mash the shift key to make single quote.
In Perl you want to use single quotes when you have a string which doesn't need to interpolate variables or escaped characters like \n, \t, \r, etc.
PHP makes the same distinction as Perl: content in single quotes will not be interpreted (not even \n will be converted), as opposed to double quotes which can contain variables to have their value printed out.
Python does not, I'm afraid. Technically seen, there is no $ token (or the like) to separate a name/text from a variable in Python. Both features make Python more readable, less confusing, after all. Single and double quotes can be used interchangeably in Python.
I chose to use double quotes because they are easier to see.
I just use whatever strikes my fancy at the time; it's convenient to be able to switch between the two at a whim!
Of course, when quoting quote characetrs, switching between the two might not be so whimsical after all...
Your team's taste or your project's coding guidelines.
If you are in a multilanguage environment, you might wish to encourage the use of the same type of quotes for strings that the other language uses, for instance. Else, I personally like best the look of '
None as far as I know. Although if you look at some code, " " is commonly used for strings of text (I guess ' is more common inside text than "), and ' ' appears in hashkeys and things like that.
I aim to minimize both pixels and surprise. I typically prefer ' in order to minimize pixels, but " instead if the string has an apostrophe, again to minimize pixels. For a docstring, however, I prefer """ over ''' because the latter is non-standard, uncommon, and therefore surprising. If now I have a bunch of strings where I used " per the above logic, but also one that can get away with a ', I may still use " in it to preserve consistency, only to minimize surprise.
Perhaps it helps to think of the pixel minimization philosophy in the following way. Would you rather that English characters looked like A B C or AA BB CC? The latter choice wastes 50% of the non-empty pixels.
I use double quotes because I have been doing so for years in most languages (C++, Java, VB…) except Bash, because I also use double quotes in normal text and because I'm using a (modified) non-English keyboard where both characters require the shift key.
' = "
/ = \ = \\
example :
f = open('c:\word.txt', 'r')
f = open("c:\word.txt", "r")
f = open("c:/word.txt", "r")
f = open("c:\\\word.txt", "r")
Results are the same
=>> no, they're not the same.
A single backslash will escape characters. You just happen to luck out in that example because \k and \w aren't valid escapes like \t or \n or \\ or \"
If you want to use single backslashes (and have them interpreted as such), then you need to use a "raw" string. You can do this by putting an 'r' in front of the string
im_raw = r'c:\temp.txt'
non_raw = 'c:\\temp.txt'
another_way = 'c:/temp.txt'
As far as paths in Windows are concerned, forward slashes are interpreted the same way. Clearly the string itself is different though. I wouldn't guarantee that they're handled this way on an external device though.

Categories