Python 3 — String Slicing & Methods
Strings are sequences of characters and one of the most frequently used data types in Python. Almost every real-world program processes text — reading user names, parsing files, displaying messages. Python's string tools are powerful and elegant.
1 Creating Strings
Python 3 — String Creation▶ Run Code
# Single and double quotes
name1 = 'Python'
name2 = "Python"
print(name1 == name2) # True — same thing
# Triple quotes for multi-line strings
poem = """Roses are red,
Violets are blue,
Python is awesome,
And so are you!"""
print(poem)
# Escape characters
path = "C:\Users\Balaji\Documents"
tab_example = "Name:\tBalaji"
newline = "Line 1\nLine 2"
print(path)
print(tab_example)
print(newline)
# Raw strings (r-prefix) — backslashes are literal
raw = r"C:UsersBalajiDocuments"
print(raw)
2 String Indexing & Slicing
Python 3 — Slicing▶ Run Code
text = "Hello, Python!"
# 0123456789...
# Single character access
print(text[0]) # H
print(text[7]) # P
print(text[-1]) # !
print(text[-6]) # P
# Slicing: [start:stop:step]
print(text[0:5]) # Hello
print(text[7:13]) # Python
print(text[:5]) # Hello (start defaults to 0)
print(text[7:]) # Python! (stop defaults to end)
print(text[::2]) # Hlo yhn (every 2nd char)
print(text[::-1]) # !nohtyP ,olleH (reversed!)
3 F-Strings & Formatting
Python 3 — F-Strings▶ Run Code
name = "Balaji"
score = 98.567
items = 5
# F-string with expressions
print(f"Hello, {name}!")
print(f"Score: {score:.2f}") # 2 decimal places
print(f"Items: {items:03d}") # pad with zeros: 005
print(f"Name upper: {name.upper()}")
print(f"2^10 = {2**10}")
# Width and alignment
print(f"{'Left':<10}|") # Left-aligned
print(f"{'Right':>10}|") # Right-aligned
print(f"{'Center':^10}|") # Centered
# Old-style formatting (still common)
msg = "Hello %s, you are %d years old." % ("Bob", 30)
print(msg)
# .format() method
msg2 = 'Product: {}, Price: $' + '{:.2f}'.format("Laptop", 999.99)
print(msg2)
4 Essential String Methods
| Method | Description | Example |
|---|---|---|
.upper() | Uppercase | "hello".upper() → "HELLO" |
.lower() | Lowercase | "HELLO".lower() → "hello" |
.strip() | Remove whitespace | " hi ".strip() → "hi" |
.split(x) | Split into list | "a,b,c".split(",") → ['a','b','c'] |
.join(lst) | Join list into string | "-".join(["a","b"]) → "a-b" |
.replace(a,b) | Replace substring | "cat".replace("c","b") → "bat" |
.find(x) | Find index of substring | "hello".find("l") → 2 |
.startswith(x) | Starts with | "Python".startswith("Py") → True |
.count(x) | Count occurrences | "banana".count("a") → 3 |
Python 3 — String Methods▶ Run Code
text = " Hello, World! Python is Amazing. "
# Cleaning
clean = text.strip()
print(clean) # No leading/trailing spaces
# Case methods
print(clean.upper()) # ALL CAPS
print(clean.lower()) # all lowercase
print(clean.title()) # Title Case
print(clean.swapcase()) # sWAP cASE
# Finding & replacing
print(clean.find("Python")) # 15 (index)
print(clean.count("o")) # 4
print(clean.replace("Amazing", "Awesome"))
# Splitting & joining
sentence = "apple,banana,cherry,mango"
fruits = sentence.split(",")
print(fruits) # ['apple', 'banana', ...]
rejoined = " | ".join(fruits)
print(rejoined) # apple | banana | ...
5 String Checking Methods
Python 3 — String Checks▶ Run Code
# Check string contents
print("Python3".isalpha()) # False (has digit)
print("Python".isalpha()) # True (only letters)
print("12345".isdigit()) # True (only digits)
print("Hello123".isalnum()) # True (letters + digits)
print(" ".isspace()) # True (only whitespace)
print("hello".islower()) # True
print("HELLO".isupper()) # True
print("Hello World".istitle()) # True
# Common validation patterns
email = "user@example.com"
print("@" in email and "." in email) # True
phone = "9876543210"
print(phone.isdigit() and len(phone) == 10) # True
6 String Concatenation & Repetition
Python 3 — Concat & Repeat▶ Run Code
# Concatenation with +
first = "Hello"
second = "World"
greeting = first + ", " + second + "!"
print(greeting) # Hello, World!
# Repetition with *
divider = "-" * 40
print(divider)
stars = "⭐" * 5
print(stars) # ⭐⭐⭐⭐⭐
# Building strings with join (efficient for many strings)
words = ["Python", "is", "a", "great", "language"]
sentence = " ".join(words)
print(sentence)
# Strings are immutable — can't modify in place
name = "Python"
# name[0] = "J" # ❌ TypeError!
name = "J" + name[1:] # ✅ Create new string
print(name)
7 Useful String Patterns
Python 3 — String Patterns▶ Run Code
# Palindrome check
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
print(is_palindrome("racecar")) # True
print(is_palindrome("A man a plan a canal Panama")) # True
print(is_palindrome("Python")) # False
# Word count
text = "the quick brown fox jumps over the lazy dog"
words = text.split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count)
# Extract file extension
filename = "tutorial.python.pdf"
parts = filename.rsplit(".", 1)
print(f"Name: {parts[0]}, Extension: {parts[1]}")
8 Coding Challenge
Build a text processor that:
- Takes a paragraph of text (hardcoded)
- Counts the total number of words, characters (excluding spaces), and sentences
- Finds the longest word
- Replaces all occurrences of a word (e.g., replace "Python" with "🐍 Python")
- Checks if it contains a specific keyword
- Outputs a formatted summary using f-strings