Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double vs. single quotes using formatted printing in python

So I was going through "Learn Python the Hard Way"

and while doing this:

formatter = "%r %r %r %r"

print formatter % (
    "I had this thing.",
    "That you could up right.",
    "But it didn't sing.",
    "So I said goodnight"
)

the output was

'I had this thing.' 'That you could up right.' "But it didn't sing." 'So I said goodnight'

But I'm not sure why the 3rd string has double strings.

like image 596
Bren Avatar asked Jan 05 '16 08:01

Bren


People also ask

Is it better to use single or double quotes in Python?

As far as language syntax is concerned, there is no difference in single or double quoted string. Both representations can be used interchangeably. However, if either single or double quote is a part of the string itself, then the string must be placed in double or single quotes respectively.

How do you print single and double quotes in Python?

If you want to use both single- and double-quotes without worrying about escape characters, you can open and close the string with three double-quotes or three single-quotes: print """In this string, 'I' can "use" either. """ print '''Same 'with' "this" string! '''

What's the difference between single quotes and double quotes in Python?

Generally, double quotes are used for string representation and single quotes are used for regular expressions, dict keys or SQL. Hence both single quote and double quotes depict string in python but it's sometimes our need to use one type over the other.

How do you print double quotes in print in Python?

Method #1 : Using backslash (“\”) This is one way to solve this problem. In this, we just employ a backslash before a double quote and it is escaped.


1 Answers

"a" and 'a' are the same strings, no difference.

The third string contains an apostrophe, so it cannot be represented as 'But it didn't sing.' because that would end the string after didn and raise a SyntaxError.

If you want to represent a string with single quote, you can do it:

"'"

or

'\''

The same with double quote:

'"'

or

"\""

If you have a string with both quotes, you can choose one:

'"\'"

or

"\"'"
like image 90
eumiro Avatar answered Nov 12 '22 03:11

eumiro