Strings and String Operations
📂 Phase 1: Python Basics, Variables, Data Types (Days 1–5) · Python ProgrammingStrings are one of the most frequently used data types in any Python program — used for everything from user-facing messages to processing text files and API responses. Python treats strings as sequences of characters, which means you can index and slice them just like a list.
Creating Strings
single = 'Hello'
double = "World"
multiline = """This string
spans multiple
lines"""
print(single, double)
print(multiline)
Single and double quotes work identically in Python — choose whichever lets you avoid escaping quotes inside the string itself.
String Indexing
Just like arrays, string indices start at 0. Negative indices count backward from the end.
word = "Python"
print(word[0]) # P — first character
print(word[5]) # n — last character
print(word[-1]) # n — also the last character, via negative indexing
String Slicing
word = "Python"
print(word[0:3]) # Pyt — characters from index 0 up to (not including) 3
print(word[2:]) # thon — from index 2 to the end
print(word[:4]) # Pyth — from the start up to index 4
print(word[::-1]) # nohtyP — reverses the entire string
The slice end index is always exclusive — word[0:3] gives 3 characters (indices 0, 1, 2), not 4. This trips up almost every beginner at least once.
Strings Are Immutable
word = "Python"
# word[0] = "J" # This raises a TypeError — strings cannot be modified in place
new_word = "J" + word[1:] # Instead, build a NEW string
print(new_word) # Jython
Common String Methods
| Method | Effect | Example |
|---|---|---|
| .upper() / .lower() | Converts case | "Hi".upper() → "HI" |
| .strip() | Removes leading/trailing whitespace | " hi ".strip() → "hi" |
| .replace(old, new) | Replaces all occurrences | "cat".replace("c","b") → "bat" |
| .split(sep) | Splits into a list | "a,b,c".split(",") → ['a','b','c'] |
| .join(iterable) | Joins a list into one string | "-".join(["a","b"]) → "a-b" |
| len(string) | Returns character count | len("hello") → 5 |
String Concatenation and Repetition
first = "Hello"
second = "World"
print(first + " " + second) # Hello World — concatenation with +
print("Ha" * 3) # HaHaHa — repetition with *
f-Strings — The Modern Way to Format
Introduced in Python 3.6, f-strings let you embed expressions directly inside a string using curly braces, prefixed with f:
name = "Vishwas"
score = 95
print(f"{name} scored {score} marks") # Vishwas scored 95 marks
print(f"Next year's score target: {score + 5}") # expressions work directly inside {}
This is far cleaner than the older .format() method or manual string concatenation with +, and it is the standard approach in modern Python code.
Interview tip: Be ready to explain why strings are immutable in Python — it allows strings to be safely shared and cached internally (string interning) and used as dictionary keys, since their value can never change unexpectedly after creation.