Strings
Explore Python's string data type, including how to create strings, use escape characters, access characters by index, understand immutability, and work with Unicode.
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:
str_1 = 'String enclosed in single quotes'print(str_1)str_2 = "String enclosed in double quotes"print(str_2)str_3 = '''String enclosed in triple quotes'''print(str_3)str_4 = 'String containing " (double qoutes) enclosed in single quotes'print(str_4)str_5 = "String containing ' (single qoute) enclosed in double quotes"print(str_5)# Either use three single quotes or doublestr_6 = '''String containing both ' and " enclosed in triple quotes'''print(str_6)multiple_lines = """Triple quotesalso allowmulti-line string."""print(multiple_lines)str_empty = ""print(str_empty)str_space = " "print(str_space)str_single = "$"print(str_single)
Explanation
Here’s the code explanation:
Lines 1–2: Create a string
str_1
enclosed in single quotes and print it.Lines 3–4: Create a string
str_2
enclosed in double quotes and print it.Lines 5–6: Create a string
str_3
enclosed in triple quotes and print it.Lines 8–9: Create a string
str_4
using single quotes to allow the inclusion of double quotes inside the string and print it. ...