views:

94

answers:

4

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?

+1  A: 

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
+1  A: 

This SO answer will give you some tips on when to use which.

Manoj Govindan
Obviously I didn't search thoroughly before asking (some Indian English and American English differences). Should I delete my question?
lalli
+2  A: 

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.

Dave Webb
+2  A: 

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