Python Strings

Learn to work with text in Python step by step

📝 What are Strings?

Strings are just text in Python! They can be words, sentences, or any characters you want to store. Think of them like digital sticky notes where you write text.


# Creating strings is easy!
name = "Alice"
message = 'Hello World!'
long_text = """This is a 
multi-line string"""

print(name)      # Prints: Alice
print(message)   # Prints: Hello World!
                                    
Text
Storage
Easy
To Use
Powerful
Tools

String Characteristics

🔒

Immutable

Cannot be changed after creation

Thread-safe Hashable
📊

Ordered Sequence

Characters have specific positions

Indexable Sliceable
🌍

Unicode Support

Supports international characters

UTF-8 Multilingual
🛠️

Rich Methods

Many built-in string operations

Manipulation Formatting

Lesson 1: Creating Your First Strings

Let's start by making some strings. You can use single quotes (') or double quotes ("):

String Creation Methods

🔹Creating strings with single and double quotes


name = 'Bob'
print(name)

message = "Hello Python!"
print(message)

🔹Creating multi-line strings


text = """
This is line 1
This is line 2
This is line 3
"""
print(text)

🔹Working with empty strings


empty_string = ""
print("Length of empty string:", len(empty_string))

🔹Mixing quotes in strings


text1 = "He said 'Hi!'"
text2 = 'She said "Hello!"'
print(text1)
print(text2)

🔹Using emojis in strings


print("I love Python! 🐍")
print("Stars ⭐⭐⭐")

Lesson 2: How Long is Your String?

You can count how many characters are in a string using len() :

Counting Characters
# Count characters in strings
name = "Alice"
message = "Hello World!"
empty = ""

print(f"'{name}' has {len(name)} characters")
print(f"'{message}' has {len(message)} characters")
print(f"Empty string has {len(empty)} characters")

# Output:
# 'Alice' has 5 characters
# 'Hello World!' has 12 characters
# Empty string has 0 characters

Lesson 3: Getting Individual Characters

You can get specific characters from a string using their position (index):

String Index Example: "PYTHON"

P
Y
T
H
O
N
0
1
2
3
4
5
Getting Characters by Position
word = "PYTHON"

# Get characters by position (starting from 0)
print("First character:", word[0])    # P
print("Second character:", word[1])   # Y
print("Third character:", word[2])    # T

# Get the last character
print("Last character:", word[5])     # N
# Or use negative indexing
print("Last character:", word[-1])    # N

# Get second to last
print("Second to last:", word[-2])    # O

Lesson 4: Getting Parts of Strings

You can get multiple characters at once using slicing:

String Slicing Basics
text = "Hello World"

# Get first 5 characters
print("First 5:", text[0:5])    # Hello

# Get characters from position 6 to end
print("From 6 to end:", text[6:])    # World

# Get first 5 characters (shortcut)
print("First 5:", text[:5])     # Hello

# Get last 5 characters
print("Last 5:", text[-5:])     # World
Fun with Slicing
word = "PYTHON"

# Get every other character
print("Every other:", word[::2])      # PTO

# Reverse the string!
print("Reversed:", word[::-1])        # NOHTYP

# Get middle characters
print("Middle part:", word[1:5])      # YTHO

Lesson 5: Changing Upper and Lower Case

Python can change the case of your text easily:

Case Conversion
text = "Hello World"

print("Original:", text)
print("UPPERCASE:", text.upper())
print("lowercase:", text.lower())
print("Title Case:", text.title())
print("Sentence case:", text.capitalize())

# Output:
# Original: Hello World
# UPPERCASE: HELLO WORLD
# lowercase: hello world
# Title Case: Hello World
# Sentence case: Hello world
Practical Example
# Making names look nice
name = "alice JOHNSON"
proper_name = name.title()
print("Proper name:", proper_name)  # Alice Johnson

# Checking passwords (case doesn't matter)
password = "SECRET123"
user_input = "secret123"

if password.lower() == user_input.lower():
    print("Password matches!")
else:
    print("Wrong password")

Lesson 6: Finding Text Inside Strings

You can search for words or characters inside strings:

Finding Text
sentence = "I love Python programming"

# Check if a word exists
if "Python" in sentence:
    print("Found Python!")

if "Java" in sentence:
    print("Found Java!")
else:
    print("Java not found")

# Find the position of a word
position = sentence.find("Python")
print(f"Python starts at position: {position}")

# Count how many times a word appears
text = "Python is fun. Python is easy. Python rocks!"
count = text.count("Python")
print(f"Python appears {count} times")

Lesson 7: Replacing Words

You can replace words or characters in strings:

Text Replacement
# Replace words in a sentence
original = "I like cats"
new_sentence = original.replace("cats", "dogs")
print("Original:", original)
print("New:", new_sentence)

# Replace multiple occurrences
text = "red car, red house, red apple"
new_text = text.replace("red", "blue")
print("Changed:", new_text)

# Fix common typos
message = "Teh quick brown fox"
fixed = message.replace("Teh", "The")
print("Fixed:", fixed)

Lesson 8: Breaking Apart and Putting Together

You can split strings into pieces or join pieces together:

Splitting Strings
# Split a sentence into words
sentence = "Python is awesome"
words = sentence.split()
print("Words:", words)  # ['Python', 'is', 'awesome']

# Split by commas
fruits = "apple,banana,orange"
fruit_list = fruits.split(",")
print("Fruits:", fruit_list)  # ['apple', 'banana', 'orange']

# Join words back together
words = ["Hello", "World", "Python"]
joined = " ".join(words)
print("Joined:", joined)  # Hello World Python

# Join with different separators
joined_with_dash = "-".join(words)
print("With dashes:", joined_with_dash)  # Hello-World-Python

Lesson 9: Putting Variables in Strings

You can insert variables into strings to make dynamic messages:

F-String Formatting (Easy Way)
# Using f-strings (put f before the quotes)
name = "Alice"
age = 25
city = "New York"

# Insert variables with {}
message = f"Hi, I'm {name}. I'm {age} years old and live in {city}."
print(message)

# You can do math inside {}
price = 19.99
tax = 0.08
total = f"Total cost: ${price + (price * tax):.2f}"
print(total)

# Format numbers nicely
big_number = 1234567
formatted = f"Population: {big_number:,}"
print(formatted)  # Population: 1,234,567

Essential String Methods

Case Methods

  • upper() - UPPERCASE
  • lower() - lowercase
  • title() - Title Case
  • capitalize() - Sentence case
  • swapcase() - sWAP cASE

Search Methods

  • find() - Find substring
  • index() - Find (with error)
  • count() - Count occurrences
  • startswith() - Check start
  • endswith() - Check end

Modification Methods

  • replace() - Replace text
  • strip() - Remove whitespace
  • split() - Split into list
  • join() - Join list to string
  • format() - Format string

Validation Methods

  • isdigit() - All digits
  • isalpha() - All letters
  • isalnum() - Letters/digits
  • isspace() - All whitespace
  • islower() - All lowercase
String Methods in Action

🔹Case Methods Demo

# Sample text for demonstrations
text = "  Hello, Python World!  "
print(f"Original: '{text}'")  # Original: '  Hello, Python World!  '

print("\n=== CASE METHODS ===")
print(f"upper(): '{text.upper()}'")  # upper(): '  HELLO, PYTHON WORLD!  '
print(f"lower(): '{text.lower()}'")  # lower(): '  hello, python world!  '
print(f"title(): '{text.title()}'")  # title(): '  Hello, Python World!  '
print(f"capitalize(): '{text.capitalize()}'")  # capitalize(): '  hello, python world!  '
print(f"swapcase(): '{text.swapcase()}'")  # swapcase(): '  hELLO, pYTHON wORLD!  '

🔹Whitespace Methods Demo

print("\n=== WHITESPACE METHODS ===")
print(f"strip(): '{text.strip()}'")  # strip(): 'Hello, Python World!'
print(f"lstrip(): '{text.lstrip()}'")  # lstrip(): 'Hello, Python World!  '
print(f"rstrip(): '{text.rstrip()}'")  # rstrip(): '  Hello, Python World!'

🔹Search Methods Demo

print("\n=== SEARCH METHODS ===")
sample = "Python is awesome and Python is fun!"
print(f"Text: '{sample}'")  # Text: 'Python is awesome and Python is fun!'
print(f"find('Python'): {sample.find('Python')}")  # find('Python'): 0
print(f"find('Java'): {sample.find('Java')}")  # find('Java'): -1
print(f"count('Python'): {sample.count('Python')}")  # count('Python'): 2
print(f"count('is'): {sample.count('is')}")  # count('is'): 2
print(f"startswith('Python'): {sample.startswith('Python')}")  # startswith('Python'): True
print(f"endswith('fun!'): {sample.endswith('fun!')}")  # endswith('fun!'): True

🔹Split and Join Demo

print("\n=== SPLIT AND JOIN ===")
sentence = "Python is a powerful programming language"
words = sentence.split()
print(f"Original: '{sentence}'")  # Original: 'Python is a powerful programming language'
print(f"Split into words: {words}")  # Split into words: ['Python', 'is', 'a', 'powerful', 'programming', 'language']
print(f"Join with '-': '{'-'.join(words)}'")  # Join with '-': 'Python-is-a-powerful-programming-language'
print(f"Join with ' | ': '{' | '.join(words)}'")  # Join with ' | ': 'Python | is | a | powerful | programming | language'

# CSV processing example
csv_line = "Alice,25,Engineer,New York"
fields = csv_line.split(',')
print(f"\nCSV parsing:")
print(f"CSV: '{csv_line}'")  # CSV: 'Alice,25,Engineer,New York'
print(f"Fields: {fields}")  # Fields: ['Alice', '25', 'Engineer', 'New York']

🔹Replace Method Demo

print("\n=== REPLACE METHOD ===")
message = "I love Java programming"
fixed = message.replace("Java", "Python")
print(f"Original: '{message}'")  # Original: 'I love Java programming'
print(f"Fixed: '{fixed}'")  # Fixed: 'I love Python programming'

# Multiple replacements
text_with_errors = "Teh quick brown fox jumps over teh lazy dog"
corrected = text_with_errors.replace("Teh", "The")
print(f"Before: '{text_with_errors}'")  # Before: 'Teh quick brown fox jumps over teh lazy dog'
print(f"After: '{corrected}'")  # After: 'The quick brown fox jumps over teh lazy dog'

🔹Validation Methods Demo

print("\n=== VALIDATION METHODS ===")
test_strings = ["123", "abc", "ABC123", "   ", "Hello World", ""]
for s in test_strings:
    print(f"'{s}': digit={s.isdigit()}, alpha={s.isalpha()}, "  # '123': digit=True, alpha=False, alnum=True, space=False, lower=False
          f"alnum={s.isalnum()}, space={s.isspace()}, lower={s.islower()}")  # (and similar output for each string in test_strings)

Practice Project: Name Badge Maker

Let's create a simple program that makes name badges:

Name Badge Generator
def make_name_badge():
    """Create a personalized name badge"""
    
    # Get user information
    first_name = input("Enter your first name: ")
    last_name = input("Enter your last name: ")
    job_title = input("Enter your job title: ")
    company = input("Enter your company: ")
    
    # Clean up the input (remove extra spaces, fix capitalization)
    first_name = first_name.strip().title()
    last_name = last_name.strip().title()
    job_title = job_title.strip().title()
    company = company.strip().title()
    
    # Create the badge
    full_name = f"{first_name} {last_name}"
    
    # Make a nice border
    border = "=" * 40
    
    # Create the badge text
    badge = f"""
{border}
           NAME BADGE
{border}

    Hello, my name is:
    
    {full_name.upper()}
    
    {job_title}
    {company}
    
{border}
"""
    
    print(badge)
    
    # Show some string info
    print(f"\nBadge Statistics:")
    print(f"Full name length: {len(full_name)} characters")
    print(f"Initials: {first_name[0]}.{last_name[0]}.")
    
    if len(full_name) > 20:
        print("⚠️ Long name - consider using a smaller font!")

# Run the badge maker
make_name_badge()

🧠 Test Your Knowledge

What does "Hello"[1] give you?

Which method makes text UPPERCASE?

What does len("Python") return?