Strings
Explore how Python strings represent sequences of characters including letters, numbers, and symbols. Learn to create strings with single, double, and triple quotes, use escape characters to include special symbols, and handle string indexing both forward and backward. Understand string immutability and the difference between ASCII and Unicode in Python 3.
String data manipulation
A string is a sequence of characters. In Python, a string is a fundamental data type that can hold any combination of characters, including letters, numbers, special symbols and punctuation marks, whitespace (spaces, tabs, newlines), and even emojis. A string can also contain a single character or be entirely empty.
For the Python interpreter to treat a sequence of characters as strings, they need to be enclosed within single, double, or triple quotation marks (either three single quotes on each end of the string or three double quotes on each end). Note that these are not considered a part of the string. Let’s have a look at the following playground to understand when each of the three styles is used. Here are some examples of strings:
Explanation
Here’s the code explanation:
Lines 1–2: Create a string
str_1enclosed in single quotes and print it.Lines 3–4: Create a string
str_2enclosed in double quotes and print it.Lines 5–6: Create a string
str_3enclosed in triple quotes and print it.Lines 8–9: Create a string
str_4using single quotes to allow the inclusion of double quotes inside ...