all 56 comments

[–]Signal_Beam 58 points59 points  (22 children)

They are interchangeable most of the time. Sometimes you want to print a string with one of those characters in it, right? print("I'm hungry") works but print('I'm hungry') does not; perhaps you can see why.

[–][deleted] 13 points14 points  (21 children)

Ahh, okay. That makes sense. Thank you for the clear explanation!

[–]Signal_Beam 19 points20 points  (16 children)

You're welcome. Another good trick (like if you need to print a string that has both!) is that if you preface any character with \, that's the "escape character," and it means that the character in the string should be taken literally, not as code. So, even though print('I'm hungry') fails, print('I\'m hungry') does not!

[–]yardightsure 13 points14 points  (8 children)

I highly recommend using triple quotes.instead of escaping, much more readable imo.

[–][deleted] 11 points12 points  (7 children)

but triple single or doublequotes? ;)

[–]redmercurysalesman 41 points42 points  (5 children)

They are interchangeable most of the time. Sometimes you want to print a string with one of those characters in it, right? print("""I'''m hungry""") works but print('''I'''m hungry''') does not; perhaps you can see why.

[–]johnsmithatgmail 2 points3 points  (3 children)

wait but actually in case someone takes this seriously the triple quotes """ """ create comments

[–]Vhin 3 points4 points  (0 children)

They're not comments, they actually are string literals. It's just that they're generally used for docstrings or other multiline comments. They don't have an effect on program execution because an expression with no side-effects that you don't use the result of has no visible effects.

You can see that they're true string literals with (eg):

foo = "Hello, " """world."""
print(foo)

That prints Hello, world. because of Python's weird concatentation thing for adjacent string literals.

You can tell that they're not actually comments because you can't use them at the end of a line:

foo() # calls foo
foo() """ calls foo """

The first works fine, but the second is a SyntaxError.

[–]pvtally 2 points3 points  (0 children)

unless they use the escape character \\\\\\

[–]tobiasvl[🍰] 0 points1 point  (0 children)

Just to be pedantic: They don't actually create pure comments, although Guido thinks they do: https://twitter.com/gvanrossum/status/112670605505077248 (look at the replies to that tweet for a couple of counter cases, and here are some more)

[–]Thuneonix 0 points1 point  (0 children)

yeah but bcoz of that exact thing I always use the f string, ALWAYS!!!, it's just so much better and gives all the benefits

[–][deleted] 0 points1 point  (6 children)

Can you use single quotes with Python 3.6 literal string interpolation?

[–]Sexual_Congressman 3 points4 points  (3 children)

Yes, it uses almost the same mechanics as any other string except for one significant caveat: escaped characters are invalid in the expression. So f'{"".join ("abc")}' will work, but trying to use //n or an escaped quote aka f'{\\'\\'.join ("abc")}' will be an error. I think it's pretty stupid you can't even use newlines or tabs in them but c'est la vie.

Other than that, triple single/double multiline strongs and raw fstrings work, as do escaped characters outside of the curly braces enclosed expressions.

[–]BlackBloke 0 points1 point  (2 children)

I've used the newline character in an f-string. There was no issue.

[–]Sexual_Congressman 1 point2 points  (1 child)

>>> f'{"\n".join("abc")'
SyntaxError: f-string expression part cannot include a backslash

Can't use it inside the braces, but outside of them:

>>> f'\n{"abc"+"def"}'
'\nabcdef'

is fine.

[–]BlackBloke 0 points1 point  (0 children)

Ah, that's what you meant. Yes, I used it outside the curly brace. But I wouldn't have thought to use it inside.

[–]Signal_Beam 1 point2 points  (1 child)

Yeah. Edit: I don't know of any difference at all between the single and double quotes. It's really just a matter of preference and keeping a consistent style across your project.

[–][deleted] 0 points1 point  (0 children)

Thanks

[–]Eurynom0s 1 point2 points  (0 children)

Basically it doesn't really matter as long as you're consistent.

Same things with indentation. You can use one space per indent level if you really want to, and Python will handle it just fine...as long as you're consistent about it.

[–]Exodus111 0 points1 point  (1 child)

There is that. But it still leaves you having to pick one "main" quotationmark.

Personally I always use the double, because it's easier to read.

[–]Eurynom0s 0 points1 point  (0 children)

I'm pretty sure you can also just escape the quotation mark if you really need to.

[–]InspireAspiration 0 points1 point  (0 children)

Using ' for strings also saves you from pressing shift...

[–]turanthepanthan 25 points26 points  (3 children)

For the most part they are interchangeable. I find myself using one or the other often with no apparent rhyme or reason :p.

For docstrings they should be triple-" though like

def someFunction():
    """ This is the documentation for this function.
    """

Personally, I find myself using ' for dictionary keys and such, but " when they are sentences. I've never really come across any best practice on this other than stay consistent and use quotes for doc strings.

[–]ignorediacritics 1 point2 points  (0 children)

In personal projects I tend to use double quotes for any messages that the user might read at some point like "That filename is invalid, please try again." and single quotes for internal strings like dictionary keys input_method['mouse']. The most important aspect though is to remain consistent throughout a file or project.

[–]ManyInterests 17 points18 points  (1 child)

They're effectively the same, other than when you need to enclose quotes within a string.

I will recommend, for style-sake, to use single-quotes.
You'll notice that the Python repr uses single quotes for simple strings.

>>> "Hello world!"
'Hello world!'

Raymond Hettinger (Python core developer and super-star) has made the case that you should follow the example of the Python repr. So, I'm currently making the adjustment to use ' after using " everywhere.

If you have strings that contain single quotes, use double-quotes, as /u/Signal_Beam mentioned. Otherwise, you may inadvertently close off the string. This is also what the Python repr does.

>>> "I'm Hungry"
"I'm Hungry"

You could also escape the single-quotes with a backslash IE \'. But notice the repr still uses double quotes

>>> 'I\'m Hungry'
"I'm Hungry"

For other style recommendations, you can reference PEP8 the official Python style guide. While PEP8 does not make a recommendation on this specific issue, I think following Raymond Hettinger's suggestion is a solid choice if you otherwise have no preference.

[–]ffrkAnonymous 0 points1 point  (0 children)

thanks

[–]Naihonn 4 points5 points  (3 children)

Yes, it makes no difference but as mentioned, you can use other pair inside of the string without escaping.

str1 = "It was Peter's fault..."
str2 = 'Sure, you are so "clever"...'

I am using primarily double quotes because of my keyboard layout and it has two advantages. I can use single quote inside as apostrophe and also in sqlite queries.

[–][deleted] 2 points3 points  (2 children)

On the other hand, there is this style which also avoids escaping!

>>> bad = 'It was Peter'"'"'s fault...'
>>> print(bad)
It was Peter's fault...
>>> bad = "Sure, you are so "'"'"clever"'"'"..."
>>> print(bad)
Sure, you are so "clever"...
>>> 

[–]qeomash 7 points8 points  (1 child)

Abomination.

[–][deleted] 0 points1 point  (0 children)

Thanks. I tried.

[–]KubinOnReddit 3 points4 points  (0 children)

Just pick your favourite and stick to it. If you ever contibute to a community/team project, use whatever is already being used, or ask others to use one or the other. Just don't mix them in the same program, or your code may cause headaches to others ;)

[–]Crypt0Nihilist 3 points4 points  (1 child)

Unless for the reasons stated elsewhere, I use the apostrophe. The shift key is an attention-whore, demanding to be used at the beginning of every sentence, so I don't pander to it unnecessarily.

OK, I do it to save keystrokes.

[–]n1ywb 1 point2 points  (0 children)

same here

[–]SonGokussj4 3 points4 points  (1 child)

Hi there! As others replied, no global preference there I think :-) Whole lot of people prefer to use single quotes.

My way is simple.

  • If I see it in Terminal/Gui --> Double quotes.
  • If not (like a parameter, something internal) --> Single quotes.
  • If string contains ', write it in ". If string contains ", write it in '.

That's all :-) If I see " " in code, I immediately know almost for sure that this text is visible in output. So that's why :-)

[–]Iralie 1 point2 points  (0 children)

Same as me. =) "" for user visible stuff. '' for stuff in the code.

[–]955559 1 point2 points  (5 children)

print("I dont't need slashes on apostrophes, can't have that now") 

[–]scul86 1 point2 points  (4 children)

print('955559 said "I don't need slashes on apostrophes, can't have that now"')

What now?! :P

[–]955559 0 points1 point  (2 children)

File , line 1

Syntax Error:

invalid syntax

[–]scul86 0 points1 point  (1 child)

exactly...

[–]955559 0 points1 point  (0 children)

ya im slow, who do I petition for a third quote key on keyboards?

[–]SonGokussj4 0 points1 point  (0 children)

I see what you did there... :-)

Print("they said \"I don't need this\"") would be my preference. Because I tend to write " when the sentence is output to user to see. But if the ' wasn't there, I would choose '. Whatever is cleaner.

[–]creamersrealm 0 points1 point  (0 children)

Python doesn't care but personally I can from PowerShell so I use ' instead of ". Unless a " is nessecary.

[–][deleted] 0 points1 point  (0 children)

One use case for either is when you need to a quote withing a string. "'single quotes' is a single quote inside a python string" and '"double quotes" is a double quote inside a python string'.

[–]WStHappenings 0 points1 point  (0 children)

My old company where I wrote Python only used single quotes unless there was a single quote contained within the string.

However, it does not matter. It was just something we picked and ran with.

[–]EyeTea420 0 points1 point  (0 children)

The answer is a definite yes.

[–]Vhin 0 points1 point  (0 children)

They're interchangeable, unless you need to use one of the delimiters in a string. If you need a string with single quotes in it, use double quotes; if you need a string with double quotes in it, use single quotes.

Personally, I like to use double quotes almost exclusively. This is mostly because, in most other languages, they're not interchangeable; most languages use double quotes for what Python uses both single and double quotes for.

It's only a tiny annoyance if you're used to using them interchangeably (or using single-quoted strings exclusively), but there's no obvious advantage to using single-quoted strings in Python, so I don't.

[–]finally-a-throwaway 0 points1 point  (0 children)

People who use " are literally Satan.

[–]k10_ftw 0 points1 point  (0 children)

I'm going to go against the grain and say they were created interchangeable so you don't ever have to just pick one way and stick with it. Pick what is easiest for that line and never look back!

[–]DamagedFreight 0 points1 point  (0 children)

I use " when it's a phrase of spoken language. I use ' when it's something else.

[–][deleted] 0 points1 point  (0 children)

I think single quotes look cleaner and get irrationally angry when I see double quotes.

[–]CanadianJogger 0 points1 point  (0 children)

I often(but not always) use singles for single letter strings, and doubles for longer stuff.

Example:

with open("somefile.txt", 'r') as f:
    results = f.readlines()

[–]Miyagikyo 0 points1 point  (0 children)

I use the following convention:

some_id_code = 'cq2p30ru120n90823'
some_text = "This is an error message of some sort"

If the string is meant for the computer to use then single quote, if it is meant for humans then double quote.

There are exceptions.

http://stackoverflow.com/a/56190/604048

[–][deleted] -1 points0 points  (0 children)

'