Introduction to Strings
Explore the fundamentals of Python strings by understanding how to create, access, and manipulate them. Learn about string indexing, slicing, immutability, concatenation, and replication to build a strong foundation in text handling.
We'll cover the following...
What is a string?
A Python string is a collection of Unicode characters. Python strings can be enclosed in single, double, or triple quotes, as shown below:
'BlindSpot'"BlindSpot"'''BlindSpot'''"""Blindspot"""
If there are characters like ', ", or \ within a string, they can be retained in two ways:
- Escape them by preceding them with a
\. - Prepend the string with
r, therefore, indicating that it is a raw string.
Multiline strings can be created in three ways:
- All but the last line ends with
\ - Enclosed within
"""some msg"""or'''some msg''' - Enclosed statements or messages within small brackets, like this:
('one msg' 'another msg')
Let’s try these ways in the code widget below:
Accessing string elements
String elements can be accessed using an index value starting with 0. A negative index value is allowed. The last character is considered to be at index -1. Positive and negative indices are shown in the figure below.
Here are examples of positive and negative indexing:
A substring can be sliced out of a string using:
s[start : end]: It extracts a substring fromstarttoend - 1.s[start :]: It extracts a substring fromstarttoend.s[: end]: It extracts a substring fromstarttoend - 1.s[-start :]: It extracts a substring from-start(included) toend.s[: -end]: It extracts a substring from beginning to-end - 1.
Using too large an index reports an error, but using too large an index while slicing is handled elegantly.
String properties
- Python strings are immutable, and they cannot be changed.
s = 'Hello'
s[0] = 'M' # rejected, attempt to mutate
s = 'Bye' # s is a variable, it can change
- Strings can be concatenated using
+.
- Strings can be replicated during printing. Replication occurs when multiplying a string (or concatenated string) by a number using the
*operator.
- Determining whether one string is part of another can be done using
in, as shown below.