Chapter 4: String Operations
Strings are ordered sequences of characters used to store text data. In Data Science, string manipulation is central to cleaning unstructured text, parsing URLs, filtering dataset names, and preparing feature data.
4.1 String Indexing and Slicing
Strings are ordered sequences of characters. You can access individual characters using indexing name[i] or extract sub-sequences using slicing name[start:stop:step].
# String Indexing
name = "Michael Jackson"
print(name[0]) # 'M' (0-based positive index)
print(name[-1]) # 'n' (negative index from right)
# String Slicing [start:stop:step]
# Start is inclusive, Stop is exclusive!
print(name[0:7]) # 'Michael'
print(name[8:15]) # 'Jackson'
# Stride (Step size)
print(name[::2]) # 'Mca Jksn' (every 2nd character)
print(name[0:7:2]) # 'Mca'
0 from the left. Negative indexing starts at -1 for the last character, -2 for second to last, and so on.
[0:7], characters at index 0 through 6 are returned. Index 7 is NOT included in the slice!
Type custom text and adjust slicing parameters [start:stop:step] to visualize character boxes and slice outputs.
4.2 Escape Sequences and Raw Strings
Escape sequences use backslashes (\) to represent special formatting characters such as newlines (\n) or tabs (\t). Prepending r creates a raw string that ignores escape sequences.
# Escape Sequences
print("Michael Jackson\nis the best") # \n inserts newline
print("Michael Jackson\tthe best") # \t inserts tab
print("Backslash: \\") # \\ prints single backslash
# Raw Strings r"..."
# Useful for file paths or Regex regex patterns
raw_path = r"C:\new_folder\test.txt" # Ignores \n and \t!
"C:\new_folder\text.txt" contain \n and \t. Without r"...", Python corrupts the path by inserting newlines and tabs!
+ & Replicating *: Strings can be joined using + (e.g. "Python" + " 3") or repeated using * (e.g. "3" * 3 = "333").
Select sample strings to observe how Python handles escape characters versus Raw String r"..." representations.
4.3 String Methods and Immutability
Strings in Python are immutable — once created, their characters cannot be modified in place. Built-in string methods (like .upper() or .replace()) always return a new string.
# String Immutability
name = "Michael Jackson"
# name[0] = "J" ❌ TypeError: 'str' object does not support item assignment
# Built-in String Methods
upper_name = name.upper() # "MICHAEL JACKSON"
replaced = name.replace('Michael', 'Janet') # "Janet Jackson"
index_j = name.find('Jack') # 8 (index position)
parts = name.split() # ['Michael', 'Jackson']
name.upper() does NOT change name! The original variable name remains "Michael Jackson". You must reassign if you want to store the result.
.find(sub) returns the index of the first character of substring (or -1 if not found). .split() splits a string into a list of words.
Apply built-in string methods to inspect output values and verify original string immutability.