A string is a sequence of characters. In other words, a string is basically a bunch of words and/or symbols.
You will use strings in almost every program that you will write, hence it is very important to understand strings properly. Now we will learn the various ways of using strings in Python:
You can specify strings using single quotes such as
'Quote me on this'
.
Strings in double quotes work exactly the same way as
strings in single quotes. An example is
"What's your name?"
You can specify multi-line strings using triple quotes. You can use single quotes and double quotes freely within the triple quotes. An example is shown below.
'''This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''
Suppose you wanted to use a string which contains a
single quote ('), how will you specify the string? For
example, the string is What's your
name?
You cannot use 'What's your
name?'
since Python will be confused as to where
the string starts and ends. In this case, we need to tell
Python that the second single quote does not specify the end of
the string. We do this by putting a backslash before that
single quote. So, we use the string as
'What\'s your name?'
. The sequence
\'
is called an escape sequence because
it causes the single quote to escape its
special meaning. There are many other types of escape sequences
as well.