Strings
String Literals
A can normally be specified by enclosing it within a pair of ''
or a pair of ""
e.g., 'How is life?'
. However, this will not work if the string has a in it e.g., 'How's life?'
is not acceptable to Python because it contains a '
which has the special meaning 'end of string', confusing Python as to which '
of the string literal indicates the end of the string. This is similarly confusing: "Say "wow""
.
An escape sequence is a sequence of characters in a string literal that is taken together and interpreted in a special way. You can use an escape sequence to include a special character in a string literal without interpreting it as a special character. Given below are some examples:
Escape Sequence | Meaning | Example | Output |
---|---|---|---|
\' | single quote | print('How\'s Life') | How's Life? |
\" | double quote | print("Say \"wow\"") | Say "wow" |
\\ | back slash | print('files\\text') | files\text |
Another use of escape sequences is to give a special meaning to a character that normally does not have a special meaning. Here are some examples:
Escape Sequence | Meaning | Example | Output |
---|---|---|---|
\t | horizontal tab | print('aaa\tbbb') | aaa bbb |
\n | line break | print('hi\nthere!') | hi there! |
You can use a pair of triple quotes to indicate a multi-line string literal.
Here is an example multi-line string that uses triple quotes.
|  → |
|
def get_email_body():
body = '''This is the first line of the email.
This is the second line.
This is the third line.
- bye!'''
return body
print(get_email_body())
This is the first line of the email.
This is the second line.
This is the third line.
- bye!
It is optional to escape '
and "
inside a mult-line string within triple quotes e.g., How's life?
in the example above.
Triple double-quotes ("""
) are commonly used to show documentation of code. Such comments are called docstrings.
The remove_head(items)
function below has a docstring that explains its behavior.
def remove_head(items):
"""Remove the first item of the items.
The list should have at least one item.
Arguments:
items -- (type: list) the list of items to be modified
"""
print('removing head of list ', items)
del items[0]
📎 Vist this page to learn more about docstrings
Working with Strings
As you have seen before, you can use +
and *
operators to concatenate and replicate strings
e.g., 'abc' + '!'*5
evaluates to 'abc!!!!!'
.
You can use indexes and slices to access characters of a string, just like if a string is a simply a list of characters.
i.e., 'Hi there'
is same as a list:
H | i | t | h | e | r | e | ! | |
---|---|---|---|---|---|---|---|---|
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
The code below shows how to use index and slice notations to get parts of a string.
|  → |
|
Strings are immutable. The following code will not work: s[0] = 'h'
You can use the in
and not in
operator to see if one string is a sub-string of another.
Examples of checking for the existence of a sub-string:
|  → |
|
String Methods
String objects have many methods (the full list is here).
Here are some string methods related to the nature of the string.
upper()
: returns a string with all characters in upper caselower()
: returns a string with all characters in lower caseisupper()
: returnsTrue
if all characters are in upper caseislower()
: returnsTrue
if all characters are in lower caseisalpha()
: returnsTrue
if the string consists only of letters and is not blank.isalnum()
: returnsTrue
if the string consists only of letters and numbers and is not blank.isdecimal()
: returnsTrue
if the string consists only of numeric characters and is not blank.isspace()
: returnsTrue
if the string consists only of spaces, tabs, and new-lines and is not blank.startswith(s)
: returnsTrue
if the substrings
appears at the start of the stringendswith(s)
: returnsTrue
if the substrings
appears at the end of the string
Examples of string methods mentioned above:
|  → |
|
|  → |
|
|  → |
|
The find(s)
method gives index of s
in the string, if it is found. It returns -1
if s
is not found.
Examples of the find()
method:
|  → |
|
The join()
method joins a list of string items while using the as a .
Examples of the join()
method:
|  → |
|
The split()
method is the opposite of join()
. It splits a string into a list of strings based on a given delimiter string. If no delimiter is given, any in the string are used as delimiters.
Some examples of using the split()
method:
|  → |
|
There are some string methods to help you to strip trailing/leading spaces.
Examples of stripping leading/trailing spaces from a string:
|  → |
|
The replace()
method can replace a character (or a phrase) with another character/phrase.
Some examples of using replace()
method:
print('face to face'.replace(' ', '-')) # replace space with a dash
print('1,2,3,4'.replace(',', '\t')) # replace comma with a tab
print('Yup, Yup, I agree'.replace('Yup', 'Yes'))
face-to-face
1 2 3 4
Yes, Yes, I agree
There are some string methods to help you to align text.
Examples of aligning text using string methods:
|  → |
|