Unit 2 · Strings in Python
Strings in Python
Learn the basics of text handling in Python: creating strings, multiline formatting, immutability, and simple operators.
Learning Objectives
By the end of this lesson, you will be able to:
- Define what a string is in Python and its core characteristics.
- Create single-line and multi-line strings.
- Explain the concept of string immutability and its implications.
- Use the concatenation (`+`) and replication (`*`) operators on strings.
- Differentiate between a string and a list.
Prerequisites
To fully understand this topic, you should be comfortable with:
- Basic Python variables and assignment.
- The concept of a data type.
Introduction
Almost every program must handle textual information (names, messages, logs, or files). In Python, text is
stored inside a string (the str data type), which is a ordered sequence of
characters.
Think of a string as a chain of characters. Each character has a specific position, and the order of characters is preserved. This ordered nature allows us to access individual characters or parts of the string using techniques like indexing and slicing, which are covered in the next topic.
Why We Need Strings
Strings are one of the most fundamental data types in any programming language. They are the backbone of how programs interact with users and handle textual data.
- User Interaction: Displaying messages, prompts, and results to the user.
- Data Storage: Storing names, addresses, passwords, and other textual information.
- File Handling: Reading from and writing to text files, log files, and configuration files.
- Web Development: Handling URLs, HTML content, and API responses.
Table of Contents
Creating Strings
In Python, strings are created by enclosing characters inside quotes. You can use single quotes
(') or double quotes ("). They work exactly the same way.
''') or triple double quotes
(""").
string1 = 'Hello' string2 = "World" print(string1, string2)
Tip
If your text contains a single quote, enclose it in double quotes (e.g., "It's a good day")
to avoid escaping syntax errors.
String Immutability (A Crucial Concept)
In Python, strings are immutable. This is a fundamental property and a very common exam topic. It means that once a string object is created in memory, its contents (the characters) **cannot be changed**.
Warning: Trying to change a character in a
string directly will raise a TypeError.
To "modify" a string, you must create a **new string** that contains the desired changes. This new string will have a different memory address.
word = "Python" print(f"Original word: {word}, ID: {id(word)}") # This line will cause an error: # word[0] = 'J' # Raises TypeError: 'str' object does not support item assignment # Instead, we create a new string: new_word = "J" + word[1:] print(f"New word: {new_word}, ID: {id(new_word)}") # The ID is different!
Basic String Operators (+ and *)
Python allows you to use standard mathematical-like symbols to manipulate text:
- Concatenation (
+): Joins two strings together. - Replication (
*): Repeats a string a given number of times.
first = "Class" second = "Room" full = first + " " + second print(full) # Class Room cheer = "Hip! " * 3 print(cheer) # Hip! Hip! Hip!
String vs. List (Key Comparison)
This comparison is a favorite in university vivas and technical interviews.
| Feature | String | List |
|---|---|---|
| Mutability | Immutable (Cannot be changed) | Mutable (Can be changed) |
| Content | Sequence of characters only. | Sequence of any data type (heterogeneous). |
| Syntax | `"Hello"` or `'Hello'` | `["H", "e", "l", "l", "o"]` |
Exam Corner & Practice
Common Mistakes
- Trying to modify a string by index (e.g., `my_string[0] = 'x'`), which causes a `TypeError`.
- Forgetting that operators like `+` and `*` create new strings, they don't modify the original ones.
- Using single quotes inside a string that is also defined with single quotes without escaping.
Exam Notes
- The most important property of a string is its **immutability**.
- Be prepared to explain the difference between a string and a list (mutability is the key).
- Concatenation (`+`) and replication (`*`) are fundamental operations.
Interview Questions
- What does it mean for a string to be immutable?
- How would you "change" a character in a string? (Answer: By creating a new string with the desired change).
- What is the difference between a string and a list of characters?
Practice Corner
# Question 1: What is the output? s1 = "py" s2 = "thon" print(s1 + s2) # Answer: "python" # Question 2: What is the output? s = "Go! " print(s * 3) # Answer: "Go! Go! Go! "
Summary
A string in Python is an **ordered** and **immutable** sequence of characters. Its immutability is its most critical feature, meaning that once created, its content cannot be altered. Any "modification" results in the creation of a new string. Basic operations include concatenation (`+`) to join strings and replication (`*`) to repeat them.