Strings
A string is a sequence of characters. Strings are basically just a bunch of words.
You will be using strings in almost every Python program that you write, so pay attention to the following part.
Single Quote
You can specify strings using single quotes such as 'Quote me on this'.
All white space i.e. spaces and tabs, within the quotes, are preserved as-is.
Double Quotes
Strings in double quotes work exactly the same way as strings in single quotes. An example is "What's your name?".
Triple Quotes
You can specify multi-line strings using triple quotes - (""" or ''') . You can use single quotes and double quotes freely within the triple quotes. An example is:
'''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."
'''Strings Are Immutable
This means that once you have created a string, you cannot change it. Although this might seem like a bad thing, it really isn't. We will see why this is not a limitation in the various programs that we see later on.
Note for C/C++ Programmers
There is no separate char data type in Python. There is no real need for it and I am sure you won't miss it.
Note for Perl/PHP Programmers
Remember that single-quoted strings and double-quoted strings are the same - they do not differ in any way.
Which quote type would be best for a multi-line string?
Can you modify a character in an existing string in Python?
Example:
name = 'praveen'
name[0] = 'P' # not allowed
name = 'Praveen' # is allowed
The format method
Sometimes we may want to construct strings from other information. This is where the format() method is useful.
Save the following lines as a file str_format.py:
age = 20
name = 'Swaroop'
print('{0} was {1} years old when he wrote this book'.format(name, age))
print('Why is {0} playing with that python?'.format(name))Output:
How It Works
A string can use certain specifications and subsequently, the
Where does Python start counting indices from?
Which of these is a valid string format in Python?
Escape Sequences
The following escape sequences have special meaning in Python strings:
- ' represents a single quote
- \n represents a new line
- \t represents a tab
- \\ represents a backslash
Example of using an escape sequence:
print('What\'s your name?') Match the escape sequences to their meanings:
Raw String
If you need to specify some strings where no special processing such as escape sequences are handled, then what you need is to specify a raw string by prefixing r or R to the string. An example is:
Note for Regular Expression Users
Always use raw strings when dealing with regular expressions. Otherwise, a lot of backwhacking may be required. For example, backreferences can be referred to as '1' or r'1'.
How do you create a raw string in Python?
What will this print?
print(r"Hello\nWorld")