4. Python Strings
Python Strings
Strings are one of the most fundamental data types in Python. A string is a sequence of characters — letters, numbers, spaces, punctuation — enclosed in quotes. Any time you work with text in Python, you are working with strings.
Python strings are immutable, which means once a string is created, it cannot be changed in place. Instead, string operations always create and return a new string. Understanding this behavior is critical to writing correct Python code.
Creating Strings
Strings can be created using single quotes, double quotes, or triple quotes. Triple-quoted strings are especially powerful because they can span multiple lines.
String Length
The built-in len() function returns the total number of characters in a string — including spaces, punctuation, and special characters. Every character counts.
The string "Hello, World!" has 13 characters: 5 + 1 (comma) + 1 (space) + 5 + 1 (exclamation) = 13.
String Indexing
Every character in a string has a position called an index. Python uses zero-based indexing, meaning the first character is at index 0, not 1. You access individual characters using square brackets.
Negative indexing lets you count from the end of the string. -1 is always the last character, -2 is second-to-last, and so on.
String Slicing
Slicing extracts a portion of a string. The syntax is string[start:end], where start is inclusive and end is exclusive (the character at end is not included).
String Methods
Python strings come with a rich library of built-in methods — functions you call on a string object using dot notation. Each method returns a new string without modifying the original.
String Concatenation
Concatenation means joining strings together. In Python, you use the + operator to concatenate strings. You can also use the * operator to repeat a string multiple times.
F-Strings (String Formatting)
F-strings (formatted string literals) are the modern, preferred way to embed variables directly inside strings. Place the letter f before the opening quote, then wrap any variable or expression in curly braces { } inside the string.
Checking String Content
Python provides two powerful keywords — in and not in — to check whether a substring exists inside a larger string. This returns a boolean: True or False.
Knowledge Check
Ready to test your understanding of 4. Python Strings?