Python strings
Learn about Python strings in COS 102. Comprehensive study materials and practice questions.
Study Notes
COS 102Python Strings: Basics, Concatenation, and Repetition
This document provides an introduction to Python strings, covering their definition, creation, basic operations like concatenation and repetition, and how to measure their length.
Learning Outcomes
- Define: Understand strings as sequences of characters used to store text.
- Manipulate: Learn to join strings using concatenation and repeat them using repetition.
- Measure: Use built-in functions to find the length of any text block.
What are Strings?
In Python, a string is simply a sequence of characters wrapped in quotes. They are fundamental for processing textual data and form the foundation of user interaction.
Creating Strings
Python offers three main ways to enclose your text:
- Single Quotes: `'Hello'`
- Double Quotes: `"Python"`
- Triple Quotes: `"""Multi-line"""` (useful for multi-line strings)
Note: Quotes must match at the beginning and end!
Concatenation
Concatenation is the process of joining two or more strings together to create a new one.
- In Python, we use the
+operator. - Example:
first = "Lego" second = "Blocks" result = first + second # result is "LegoBlocks"
The "No Space" Rule (Important Tip)
The + operator does not add spaces automatically. You must add them yourself!
- Example:
name = "Alice" + " " + "Smith" # Output: "Alice Smith"
Repetition
Repetition creates multiple copies of a string and joins them together.
- We use the
*operator followed by an integer. - Example:
laugh = "Ha! " print(laugh * 3) # Output: "Ha! Ha! Ha! "
The `len()` Function
The len() function counts the number of characters in a string.
- Crucial: It counts spaces and punctuation marks too!
- Example:
(The string "Hello World!" has 12 characters, including the space and exclamation mark.)text = "Hello World!" print(len(text)) # 12
String Operators Summary
| Operator | Name | Action | Example |
|---|---|---|---|
+ |
Concatenation | Joins two strings | "Hi" + "!" → "Hi!" |
* |
Repetition | Repeats a string | "A" * 3 → "AAA" |
len() |
Length | Counts characters | len("Cat") → 3 |
Avoid the TypeError
- Mixing Types: You cannot add a string and a number directly.
"Age: " + 20→ Error!
- The Fix: Convert the number to a string first using
str()."Age: " + str(20)→"Age: 20"
Predict the Output!
"5" + "5"Answer:
"55"(Concatenates the string "5" with the string "5")"Go!" * 2Answer:
"Go!Go!"(Repeats the string "Go!" two times)len("Python 3")Answer:
8(Counts all characters, including the space)
Next Steps
Strings are the foundation of all user interaction in Python. The next chapter will cover String Slicing and Formatting, providing more advanced techniques for manipulating textual data.