Python Strings
# Python Strings
Welcome to Chapter 9! Strings are one of the most commonly used data types. From usernames to emails, from file paths to API responses — strings are everywhere.
---
1. Learning Objectives
- Create strings using different quote styles.
- Use indexing and slicing to extract characters.
- Master essential string methods.
- Format strings using f-strings and .format().
- Understand string immutability.
---
2. String Creation
```python id="py9ex1" # Single quotes name = 'Alice'
# Double quotes greeting = "Hello, World!"
# Triple quotes (multi-line) bio = """My name is Alice. I love Python programming. I am 25 years old."""
# String with special characters quote = "She said \"Hello!\"" path = 'C:\\Users\\Alice' rawpath = r'C:\Users\Alice'
print(name, greeting) print(bio)
python id="py9_ex2" text = "Python"
# Positive indexing (left to right, 0-based) print(text[0]) # P print(text[1]) # y print(text[5]) # n
# Negative indexing (right to left) print(text[-1]) # n print(text[-2]) # o print(text[-6]) # P
String Indexing: P y t h o n 0 1 2 3 4 5 (positive) -6 -5 -4 -3 -2 -1 (negative)
python id="py9_ex3" text = "Hello, Python!"
print(text[0:5]) # Hello print(text[7:13]) # Python print(text[:5]) # Hello (from start) print(text[7:]) # Python! (to end) print(text[::2]) # Hlo yhn (every 2nd char) print(text[::-1]) # !nohtyP ,olleH (reversed)
# Practical: Extract domain from email email = "user@example.com" domain = email[email.index("@") + 1:] print(f"Domain: {domain}") # example.com
python id="py9_ex4" text = " Hello, Python World! "
# Case methods print(text.upper()) # " HELLO, PYTHON WORLD! " print(text.lower()) # " hello, python world! " print(text.title()) # " Hello, Python World! " print(text.capitalize()) # " hello, python world! " print(text.swapcase()) # " hELLO, pYTHON wORLD! "
# Whitespace print(text.strip()) # "Hello, Python World!" print(text.lstrip()) # "Hello, Python World! " print(text.rstrip()) # " Hello, Python World!"
# Search print(text.find("Python")) # 9 print(text.count("o")) # 2 print(text.startswith(" He")) # True print(text.endswith("! ")) # True
# Replace print(text.replace("Python", "Java"))
# Split and Join words = "apple,banana,cherry".split(",") print(words) # ['apple', 'banana', 'cherry']
joined = " | ".join(words) print(joined) # apple | banana | cherry
# Validation print("hello123".isalnum()) # True print("hello".isalpha()) # True print("12345".isdigit()) # True print(" ".isspace()) # True
python id="py9_ex5" # Concatenation first = "Hello" last = "World" full = first + " " + last print(full) # Hello World
# Repetition line = "=-" * 20 print(line)
# Membership print("Python" in "I love Python") # True print("Java" not in "I love Python") # True
# Length print(len("Hello")) # 5
python id="py9ex6" text = "Hello" # text[0] = "h" # ❌ TypeError! Strings are immutable
# Create a new string instead newtext = "h" + text[1:] print(newtext) # hello
# Or use replace newtext = text.replace("H", "h") print(new_text) # hello
python id="py9_ex7" word = input("Enter a word: ").lower().strip() if word == word[::-1]: print(f"'{word}' is a palindrome! ✅") else: print(f"'{word}' is NOT a palindrome ❌")
python id="py9ex8" sentence = "Python is amazing and Python is powerful" words = sentence.lower().split() wordcount = {}
for word in words: wordcount[word] = wordcount.get(word, 0) + 1
for word, count in word_count.items():
print(f" '{word}': {count}")
``
---
9. Common Mistakes
-
1.
Index out of range: "Hello"[10]
causes IndexError.
- 2. Trying to modify strings: Strings are immutable.
-
3.
Confusing find()
andindex():find()returns -1 if not found;index()raises ValueError.
-
4.
Forgetting that split()
returns a list, not a string.
---
10. MCQs with Answers
Q1: "Python"[-1] returns:
A) P B) n C) o D) Error
Answer: B
Q2: "Hello"[1:4] returns:
A) Hel B) ell C) ello D) Hell
Answer: B
Q3: Strings in Python are: A) Mutable B) Immutable C) Both D) Neither Answer: B
Q4: "hello".upper() returns:
A) Hello B) HELLO C) hELLO D) hello
Answer: B
Q5: "a,b,c".split(",") returns:
A) "abc" B) ["a","b","c"] C) ("a","b","c") D) {"a","b","c"}
Answer: B
Q6: " ".join(["a","b","c"]) returns:
A) abc B) a b c C) a,b,c D) [a,b,c]
Answer: B
Q7: "Python"[::-1] returns:
A) Python B) nohtyP C) Pytho D) Error
Answer: B
Q8: "hello".find("xyz") returns:
A) 0 B) False C) -1 D) Error
Answer: C
Q9: len("Hello") returns:
A) 4 B) 5 C) 6 D) Error
Answer: B
Q10: Which checks if string is all digits? A) isnum() B) isdigit() C) isnumber() D) isint() Answer: B
---
11. Interview Questions
- 1. Are strings mutable in Python? No. Any operation creates a new string.
-
2.
Difference between find()
andindex()?find()returns -1 on failure;index()raises ValueError.
-
3.
How to reverse a string? text[::-1]
.
-
4.
How to check if a string is a palindrome? s == s[::-1]
.
- 5. What is string interning? Python caches small strings for performance, so identical strings may share memory.
---
12. Summary
- Strings are immutable sequences of characters.
-
Use indexing ([0]
,[-1]) and slicing ([1:4],[::-1]).
-
Key methods: upper()
,lower(),strip(),split(),join(),replace(),find().
- Use f-strings for formatting.
-
Strings support +
(concatenation),*(repetition),in` (membership).
---
13. Next Chapter Recommendation
In Chapter 10: Lists in Python, you'll learn about Python's most versatile data structure with list methods, comprehensions, and a to-do list project! 🚀