Chapter 13: String Methodsยถ

๐Ÿš€ Open Notebookยถ

Open In Colab Open In Kaggle

๐Ÿ“บ Video Tutorialยถ

Watch on YouTube

String methods in Python are easy! ใ€ฐ๏ธ (12:14)

๐Ÿ“š What Youโ€™ll Learnยถ

Master Pythonโ€™s powerful string manipulation methods to transform and analyze text!

๐ŸŽฏ Learning Objectivesยถ

  • Use common string methods (.upper(), .lower(), .title(), etc.)

  • Find and replace substrings

  • Validate string content

  • Combine multiple string operations

๐Ÿ“– Concept Explanationยถ

Strings in Python come with many built-in methods for manipulation. Methods are functions that belong to an object (in this case, strings).

Common String Methodsยถ

Method

Description

Example

.upper()

Convert to uppercase

"hello".upper() โ†’ "HELLO"

.lower()

Convert to lowercase

"HELLO".lower() โ†’ "hello"

.title()

Capitalize first letter of each word

"hello world".title() โ†’ "Hello World"

.capitalize()

Capitalize first letter only

"hello world".capitalize() โ†’ "Hello world"

.find()

Find substring index

"hello".find("e") โ†’ 1

.replace()

Replace substring

"hello".replace("l", "L") โ†’ "heLLo"

.isdigit()

Check if all digits

"123".isdigit() โ†’ True

.isalpha()

Check if all letters

"abc".isalpha() โ†’ True"

.strip()

Remove whitespace

"  hi  ".strip() โ†’ "hi"

.split()

Split into list

"a,b,c".split(",") โ†’ ['a','b','c']

๐Ÿ’ก Examplesยถ

Example 1: Case Conversionยถ

name = "john DOE"
print(name.upper())      # JOHN DOE
print(name.lower())      # john doe
print(name.title())      # John Doe
print(name.capitalize()) # John doe

Example 2: Finding Substringsยถ

text = "Python Programming"
print(text.find("Pro"))      # 7 (index where "Pro" starts)
print(text.find("Java"))     # -1 (not found)
print("Pro" in text)         # True (membership check)

Example 3: Replacing Textยถ

phone = "123-456-7890"
clean = phone.replace("-", "")
print(clean)  # 1234567890

message = "Hello World"
new_msg = message.replace("World", "Python")
print(new_msg)  # Hello Python

Example 4: Validationยถ

user_input = "12345"
if user_input.isdigit():
    number = int(user_input)
    print(f"Valid number: {number}")
else:
    print("Please enter only digits")

โœ๏ธ Practice Exercisesยถ

  1. Create a program that converts usernames to lowercase

  2. Clean phone numbers by removing spaces and dashes

  3. Validate email format (contains @ and .)

  4. Count how many times a letter appears in a word

  5. Create a function that capitalizes names properly

  6. Build a simple text processor that removes extra spaces

๐Ÿ“ More Useful Methodsยถ

.count(substring)ยถ

text = "hello world"
print(text.count("l"))  # 3

.startswith() and .endswith()ยถ

filename = "document.pdf"
print(filename.endswith(".pdf"))  # True
print(filename.startswith("doc")) # True

.strip(), .lstrip(), .rstrip()ยถ

text = "   hello   "
print(text.strip())   # "hello" (both sides)
print(text.lstrip())  # "hello   " (left side)
print(text.rstrip())  # "   hello" (right side)

.split() and .join()ยถ

# Split string into list
sentence = "Python is awesome"
words = sentence.split()  # ['Python', 'is', 'awesome']

# Join list into string
joined = " ".join(words)  # "Python is awesome"
csv = ",".join(words)     # "Python,is,awesome"

๐ŸŽฎ Real-World Examplesยถ

Email Validatorยถ

email = input("Enter email: ")
if "@" in email and "." in email:
    domain = email.split("@")[1]
    print(f"Domain: {domain}")
else:
    print("Invalid email format")

Username Formatterยถ

username = input("Username: ")
username = username.strip().lower().replace(" ", "_")
print(f"Formatted username: {username}")

Password Strength Checkerยถ

password = input("Enter password: ")
has_digit = any(c.isdigit() for c in password)
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)

if len(password) >= 8 and has_digit and has_upper and has_lower:
    print("Strong password!")
else:
    print("Weak password")

๐Ÿš€ Challenge Projectsยถ

  1. Text Analyzer: Count words, letters, vowels, consonants

  2. Name Formatter: Handle various name formats (JOHN DOE, john doe, etc.)

  3. Censorship Filter: Replace bad words with asterisks

  4. Acronym Generator: Create acronyms from phrases (e.g., โ€œFor Your Informationโ€ โ†’ โ€œFYIโ€)

  5. Text Reverser: Reverse words and sentences in different ways

๐ŸŽ“ Key Takeaways from Videoยถ

  1. Strings are text data enclosed in quotes

  2. Define functions using the def keyword

  3. Use if-elif-else for conditional logic

๐Ÿ’ก These points cover the main concepts from the video tutorial to help reinforce your learning.

๐Ÿ”— Next Chapterยถ

Continue to Chapter 14: Indexing to learn how to access individual characters!