Strings
In this chapter you will learn to create, format, modify and delete strings in Python. Also, you will be introduced to various string operations and functions and methods.
What is String in Python?
A string is a sequence of characters.
A character is simply a symbol. For example, the English language has 26 characters.
Computers do not deal with characters, they deal with numbers (binary). Even though you may see characters on your screen, internally it is stored and manipulated as a combination of 0s and 1s.
This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and Unicode are some of the popular encodings used.
In Python, a string is a sequence of Unicode characters. Unicode was introduced to include every character in all languages and bring uniformity in encoding. You can learn about Unicode from Python Unicode.
How to create a string in Python?
Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings.
When you run the program, the output will be:
How to access characters in a string?
We can access individual characters using indexing
and a range of characters using slicing
. Index starts from 0
.
Trying to access a character out of index range will raise an IndexError
. The index must be an integer. We can't use floats or other types, this will result into TypeError
.
Python allows negative indexing for its sequences.
The index of -1
refers to the last item, -2
to the second last item and so on. We can access a range of items in a string by using the slicing operator :
(colon).
Slicing in lay terms means to extract a part of a sequence.
Example:
This means that we can extract a part of a string starting from index 0
to index 5
and from index 6
to the end.
If we try to access an index out of the range or use numbers other than an integer, we will get errors.
Example:
Slicing can be best visualized by considering the index to be between the elements as shown below.
If we want to access a range, we need the index that will slice the portion from the string.
Example:
How to change or delete a string?
Strings are immutable. We can't change a string by assigning a new value to it.
We cannot delete or remove characters from a string. But deleting the string entirely is possible using the del
keyword.
The reason for this is that strings are immutable.
Python String Operations
There are many operations that can be performed with strings which makes it one of the most used data types in Python.
Concatenation of Two or More Strings
Joining of two or more strings into a single one is called concatenation.
The +
operator does this in Python. Simply writing two string literals together also concatenates them.
The *
operator can be used to repeat the string for a given number of times.
Writing two string literals together also concatenates them like +
operator.
If we want to concatenate strings in different lines, we can use parentheses.
Iterating Through a string
We can iterate through a string using a for loop. Here is an example to count the number of 'l's in a string.
String Membership Test
We can test if a substring exists within a string or not, using the keyword in.
Built-in functions to Work with Python
Various built-in functions that work with sequence work with strings as well.
Some of the commonly used ones are enumerate()
and len()
. The enumerate()
function returns an enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful for iteration.
Similarly, len()
returns the length (number of characters) of the string.
Python String Formatting
Escape Sequence
If we want to print a text like He said, "What's there?"
, we can neither use single quotes nor double quotes. This will result in a SyntaxError
as the text itself contains both single and double quotes.
One way to get around this problem is to use triple quotes. Alternatively, we can use escape sequences.
An escape sequence starts with a backslash and is interpreted differently.
If we use a single quote to represent a string, all the single quotes inside the string must be escaped. Similar is the case with double quotes.
Here is how it can be done to represent the above text.
Here is a list of all the escape sequences supported by Python.
Examples:
The format()
Method for Formatting Strings
The format()
method that is available with the string object is very versatile and powerful in formatting strings. Format strings contain curly braces {}
as placeholders or replacement fields which get replaced.
We can use positional arguments or keyword arguments to specify the order.
The format()
method can have optional format specifications. They are separated from the field name using colon. For example, we can left-justify <
, right-justify >
or center ^ a string in the given space.
We can also format integers as binary, hexadecimal, etc. and floats can be rounded or displayed in the exponent format. There are tons of formatting you can use.
Old style formatting
We can even format strings like the old sprintf()
style used in C programming language. We use the %
operator to accomplish this.
Common Python String Methods
There are numerous methods available with the string object. The format()
method that we mentioned above is one of them. Some of the commonly used methods are lower()
, upper()
, join()
, split()
, find()
, replace()
etc
Here is a table of all the string methods.
Note: The above table is not exhaustive.
Last updated