Chapter 1 of ?
python 12 min read

Python for Data Science — Chapter 4: String Operations

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 Indexing & Slicing
0-Based & Negative Indices
4.2 Escape Sequences
Newlines \n, Tabs \t, Raw Strings r""
🛠️
4.3 String Methods
Immutability & Built-in Functions

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: "Michael Jackson" Positive indices count from the left (0); negative indices count from the right (-1) 0 M -15 1 i -14 2 c -13 3 h -12 4 a -11 5 e -10 6 l -9 7 -8 8 J -7 9 a -6 10 c -5 11 k -4 12 s -3 13 o -2 14 n -1 index 6 → 'l' index 13 → 'o' index -1 → 'n' (last) index -15 → 'M' (first)
Slicing and Striding A stride (step) selects every Nth character; slicing selects a range name[::2] — stride of 2, every 2nd character name[::2] M i c h a e l J a c k s o n Result: "McalJcsn" name[0:4:2] — every 2nd character, up to index 4 name[0:4:2] M i c h a e l J a c k s o n Result: "Mc"
# 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-Based & Negative Indexing: Python counts indices starting at 0 from the left. Negative indexing starts at -1 for the last character, -2 for second to last, and so on.
Exclusive Stop Rule: In slicing [0:7], characters at index 0 through 6 are returned. Index 7 is NOT included in the slice!
Interactive String Indexing & Slicing Explorer

Type custom text and adjust slicing parameters [start:stop:step] to visualize character boxes and slice outputs.

Slice Evaluation OutputLength: 7
>>> Expression: name[0:7:1] >>> Sliced Result: "Michael"
Try It Yourself »

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 A backslash marks the start of a special character inside a string CODE WHAT IT MEANS RENDERED OUTPUT "Hi\n Bye" \n = new line Hi Bye "Hi\t Bye" \t = tab Hi Bye "Hi \\\\ Bye" \\\\ = one literal backslash Hi \ Bye r"Hi\n Bye" the r prefix means "raw" — ignore escape sequences Hi\n Bye
# 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!
Why Raw Strings Matter: Windows file paths like "C:\new_folder\text.txt" contain \n and \t. Without r"...", Python corrupts the path by inserting newlines and tabs!
Concatenation + & Replicating *: Strings can be joined using + (e.g. "Python" + " 3") or repeated using * (e.g. "3" * 3 = "333").
Escape Sequence & Raw String Inspector

Select sample strings to observe how Python handles escape characters versus Raw String r"..." representations.

Formatted String OutputParsed
Line 1: Michael Jackson Line 2: is the best
Try It Yourself »

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.

Combining Strings — and Why They're Immutable CONCATENATION (+) "Michael Jackson" + " is the best" → "Michael Jackson is the best" REPLICATION (*) "ha" * 3 → "hahaha" STRINGS ARE IMMUTABLE — you can't change one in place: ✗ name[0] = "x" TypeError: 'str' object does not support item assignment ✓ name = name + " is the best" This doesn't edit the old string — it creates a brand-new one. Every string "operation" you've seen here returns a new string. The original is never modified.
Common String Methods A method applied to a string returns a brand-new string (or number) — it never edits the original METHOD CALL RESULT NOTE "Michael Jackson".upper() "MICHAEL JACKSON" Converts every character to uppercase "Michael Jackson" .replace("Michael","Janet") "Janet Jackson" Swaps a substring "Michael Jackson".find("Jack") 8 Index where the match starts "Michael Jackson".find("Elvis") -1 -1 means "not found"
# 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']
Immutability Guarantee: Calling name.upper() does NOT change name! The original variable name remains "Michael Jackson". You must reassign if you want to store the result.
Searching & Splitting: .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.
Interactive String Method Studio

Apply built-in string methods to inspect output values and verify original string immutability.

Method Execution OutputImmutability Preserved
>>> Original string: "Michael Jackson" >>> Method: name.upper() >>> Returned Value: "MICHAEL JACKSON" >>> Original Unchanged: "Michael Jackson"
Try It Yourself »

Chapter 4 Quiz — Test Your Knowledge

1. What is the value of "Michael Jackson"[-1]?

2. What does the slice "Michael Jackson"[0:7] return?

3. Why do we use Raw Strings r"C:\new_folder" for file paths?

4. What happens to original variable text after running text.upper()?

Done with this chapter?
Mark it complete to track your progress and unlock your certificate.
Next Up

Learner Reviews

Write a Review
Share your experience to help other learners.
Your Rating *