Strings
Strings are a fundamental data type used to represent text. Whether it’s a single
character or a paragraph, any text enclosed within either single quotes (' '
) or double quotes
(" "
) is considered a string
in Python. Strings serve as the building blocks for text
manipulation, and Python equips us with a rich set of built-in methods, or manipulators, to
operate on strings. You can perform operations like changing letter cases, slicing (and more)
to manipulate and extract valuable information from text data.
Creating a string
is straightforward. You assign any alphanumeric value inside single or double
quotes to a variable name using the assignment operator (=
):
Tip
Strings can be enclosed in either single quotes ('') or double quotes (""), allowing you
flexibility in your code. Moreover, if a string needs to contain both types of quotes, you
can use the backslash (\
) as an escape character to ensure Python interprets the characters
correctly.
Concatenating Strings
Strings can be combined with simple plus (+
) signs:
Basic Concatenation | |
---|---|
Would output:
F-Strings
Introduced in version 3.6 (3.13.3 is current as of Summer 2025), “F-Strings” are a much-improved way to build strings in Python. Simply precede a string with f before the opening quotation. Then, any variable can be surrounded by curly braces {}, removing the need to cast variables of various types. For example:
Would produce:
String Methods
Strings can accept methods which alter the contents of the string. Some examples of string methods that are built into Python include:
Sample String Methods | |
---|---|
Returns:
Adding & Removing Whitespace
Special characters can be added to strings that add whitespace. These include:
\t
which adds a tab (4 spaces)\n
which adds a newline
Adding Tabs and New Lines to Output | |
---|---|
Returns:
Whitespace can also be stripped out using string methods. These include strip()
(both sides),
rstrip()
(right side), and lstrip()
(left side).
Stripping Whitespace in Strings | |
---|---|
Would result with:
Hello I am Albert Einstein .
Hello I am Albert Einstein.
Hello I am Albert Einstein.
Hello I am Albert Einstein .
Tip
Strings can also be sliced - see Slicing Sequences for more details.