Python: Strings
Master text manipulation in Python. From basic slicing to advanced formatting and built-in methods, strings are one of Python's most powerful and flexible data types.
Creating Strings
In Python, strings are sequences of characters used to store and represent text-based information. You can create strings by enclosing characters in single quotes (' '), double quotes (" "), or triple quotes for multi-line text.
String Creation
PythonDifferent ways to define string literals.
Indexing and Slicing
Because strings are sequences, every character has a specific position called an index. Python indexing starts at 0. You can also use negative indexing to count backwards from the end of the string (starting at -1).Slicing allows you to extract a range of characters.
Slicing Syntax
The syntax for slicing is [start:stop:step].
- start: The beginning index (inclusive)
- stop: The ending index (exclusive)
- step: The stride between indices (defaults to 1)
- Negative indices count from the end: -1 is the last character
Indexing and Slicing Examples
PythonAccessing parts of a string.
Concatenation, Repetition, and Length
You can combine strings using the + operator (concatenation) and repeat them using the * operator. The len() function returns the total number of characters in a string.
Basic String Operations
PythonJoining and measuring strings.
String Immutability
A critical concept in Python is that strings are immutable. This means that once a string object is created, its contents cannot be changed. If you want to modify a string, you must create a new one.
Why Immutability?
Immutability makes strings hashable (so they can be dictionary keys) and helps with memory efficiency.
- You cannot do: s[0] = "A"
- To "change" a string, reassign the variable: s = "A" + s[1:]
- This behavior ensures consistency across the program
Dealing with Immutability
PythonUpdating a string involves creating a new reference.
Escape Characters and Raw Strings
Escape characters allow you to include special characters in a string, such as newlines (\n) or quotes. If you prefix a string with r, it becomes a raw string, and backslashes are treated as literal characters.
Escapes and Raw Text
PythonHandling backslashes and special symbols.
Methods: Case and Whitespace
Python provides a rich set of built-in methods to transform text. Case methods change the capitalization, while strip methods remove unwanted whitespace.
Transforming Case and Space
PythonCleaning up user input or formatting titles.
Methods: Search, Replace, and Split
These methods allow you to locate substrings, replace patterns, or break a string into a list of parts based on a delimiter.
Searching and Splitting
PythonBreaking down and rearranging text.
Methods: Validation and Padding
Validation methods check if a string consists entirely of certain characters (like digits or letters). Padding methods allow you to align text or add leading zeroes.
Validation and Alignment
PythonVerifying data and formatting output widths.
Encoding and Decoding
Strings in Python 3 are Unicode by default. To convert text to binary data (bytes) for network transmission or file storage, you use encode(). To convert bytes back to a string, you use decode().
Encoding to Bytes
PythonMoving between strings and raw binary data.
String Formatting
Formatting allows you to inject variables into strings. While older styles like the% operator and .format() method are still common, f-strings (introduced in Python 3.6) are the modern standard.
Three Styles of Formatting
PythonFrom the oldest to the most modern syntax.
Comparison and Membership
You can compare strings using standard operators like ==(checks equality) or <(checks lexicographical/alphabetical order). The in keyword checks if a substring exists inside another string.
Evaluating Strings
PythonLogic and membership tests.
Quiz - Test Your Knowledge
Test your understanding of string manipulation in Python with these eight questions. Remember that strings are immutable and indexed starting at zero.
Knowledge Check
1. How do you create a raw string in Python?
2. What is the result of "Python"[1:4]?
3. Which property describes the fact that strings cannot be changed after creation?
4. Which method removes leading and trailing whitespace?
5. How do you check if the string "apple" exists in "apple pie"?
6. What does the zfill() method do?
7. Which formatting method is considered the most modern and readable (Python 3.6+)?
8. What is the output of "Hi" * 3?