String Literals
String literals can be written with a pair of single quotes, double quotes, and Triple quotes.Strings with single quotes and double quotes are essentially the same. For example:
>>> 'hello world'
'hello world'
>>> "hello world"
'hello world'
The reason to support both is that Python supports you to embed a quote character for the other variety inside a string without escaping it with a backslash. A single quote character can be embedded in a string enclosed in double quote characters, and vice versa:
>>> "There is a 't' in the word 'cat'."
"There is a 't' in the word 'cat'."
>>> 'There is a "t" in the word "cat".'
'There is a "t" in the word "cat".'
The following two are invalid strings:
>>> 'There is a 't' in the word 'cat'.'
SyntaxError: invalid syntax
>>> "There is a "t" in the word "cat"."
SyntaxError: invalid syntax
When a string is too long, it may be written into multiple lines, with a pair of triple quotes around it. For instance:
>>> s = '''I am going
to write a
long sentence'''
>>> s
'I am going\nto write a\nlong sentence'
Sometimes a string is inside a pair of parentheses and each line is inside a pair of quotes:
>>> s = ('I am going'
'to write a'
'long sentence')
>>> s
'I am goingto write along sentence'
Please notice that the two strings above are different. The first string inside a pair of triple quotes contains a newline characters at the end of each line, but the second one does not.
Escape Sequences and Raw Strings
Similar to many common programming languages, strings in Python may have escape sequences, which are backslashes used to introduce special byte codings. For example:>>> s = '1\t2\n3'
>>> print s
1 2
3
>>> s = 'c:\\new\\test.py'
>>> print s
c:\new\test.py
In the code above, \t means a horizontal tab, \n means a newline, and \\ stands for a \.
Similar to C/++, the character \0 is a character with ASCII value 0. However, the \0 character does not terminate a string:
>>> s = 'ab\0cd'
>>> s
'ab\x00cd'
The character \ appears frequently in paths, it prone to make mistakes on paths for many programmers due to escape sequences. For instance, if the path in the code above 'c:\\new\\test.py' is written as 'c:\new\test.py', it is not a valid path anymore.
Raw strings make life easy. If the letter r (in lowercase or uppercase) appears just before the opening quote of a string, the escape mechanism gets turned off. For instance:
>>> s = r'c:\new\test.py'
>>> s
'c:\\new\\test.py'
Characters and Strings
In many programming languages such as C# and Java, the types for characters and strings are different. However, a single character is essentially a string with length 1. For example:>>> type('a')
<type 'str'>
>>> type('abcdefg')
<type 'str'>