1

I'm kinda' new to python, but I have already written many programs including some like download-managers, games and text-editors which require a lot of string manipulation.
For representing a string literal I use either single or double inverted commas.. whichever comes to my mind first at that time.

Although I haven't yet faced any trouble. My question: is there any purpose for which python allows both or is it just for compatibility, usability etc?

lalli
  • 6,083
  • 7
  • 42
  • 55
  • 1
    Never heard quote marks called inverted commas before. Details are here: http://docs.python.org/reference/lexical_analysis.html#string-literals These details are different for python 3 – MattH Sep 07 '10 at 10:36
  • OK, that's why the results in the searches were so weird. This is a repeat then. Should I delete the question? – lalli Sep 07 '10 at 16:43
  • This [SO answer](http://stackoverflow.com/questions/56011/single-quotes-vs-double-quotes-in-python/56190#56190) will give you some tips on when to use which. – Manoj Govindan Sep 07 '10 at 10:32

3 Answers3

5

There is no difference between "string" and 'string' in Python, so, as you suggest, it's just for usability.

>>> 'string' == "string"
True

You can also use triple quotes for multiline strings:

>>> mystring = """Hello
... World!"""
>>> mystring
'Hello\nWorld!'

Another trick is that adjacent string literals are automatically concatenated:

>>> mystring = "Hello" 'World!'
>>> mystring
'HelloWorld!'

There are also string prefixes which you can read about in the documentation.

David Webb
  • 190,537
  • 57
  • 313
  • 299
4

It means you can easily have a string with either single or double quotes in it without needing any escape characters. So you can do:

a = 'The knights who say "ni!"'
b = "We're knights of the Round Table, we dance whene'er we're able."
neil
  • 3,387
  • 1
  • 14
  • 11
1

Just for compatibility and usability.

It is sometimes useful when you have one of them embedded in the string, so I would use "Who's there?" compared to 'He says: "Hello"'.

The other option is of course triple quoted strings, like

"""This is a long string that can contain single quotations like ' or ".
It can also span multiple lines"""

which is equal to

'''This is a long string that can contain single quotations like ' or ".
It can also span multiple lines'''
Muhammad Alkarouri
  • 23,884
  • 19
  • 66
  • 101