String Functions and Methods

What Are String Methods?

String methods are built-in functions that work specifically with strings (text in quotes). They let you transform, check, or manipulate strings easily.

Syntax:

result = text.method_name()

The method comes after the string variable with a dot (.) in between.

Example:

name = "Alice"
name_upper = name.upper()  # Convert to uppercase
print(name_upper)  # Output: ALICE

Important: Most string methods don’t change the original string - they return a new string with the changes.

greeting = "hello"
greeting.upper()  # Returns "HELLO" but doesn't change greeting
print(greeting)    # Still prints: hello

# To keep the change, assign it to a variable:
greeting_upper = greeting.upper()
print(greeting_upper)  # Prints: HELLO

Try it:

greeting = "hello" greeting.upper() # Returns "HELLO" but doesn't change greeting print(greeting) # Still prints: hello greeting_upper = greeting.upper() print(greeting_upper) # Prints: HELLO


Common String Methods

Case Conversion Methods

Method What It Does Example Result
.upper() Convert all letters to UPPERCASE "hello".upper() "HELLO"
.lower() Convert all letters to lowercase "HELLO".lower() "hello"
.capitalize() Capitalize only the first letter "hello world".capitalize() "Hello world"
.title() Capitalize the first letter of each word "hello world".title() "Hello World"

Examples:

city = "new york"
print(city.upper())        # NEW YORK
print(city.capitalize())   # New york
print(city.title())        # New York

# Original string unchanged
print(city)                # new york

Try it:

city = "new york" print(city.upper()) # NEW YORK print(city.capitalize()) # New york print(city.title()) # New York # Original string unchanged print(city) # new york

Common use case: Making comparisons case-insensitive

user_answer = input("Continue? (yes/no): ")

# This works regardless of how user types it: "YES", "Yes", "yes", "yES" etc.
if user_answer.lower() == "yes":
    print("Continuing...")
else:
    print("Stop!")

Whitespace Methods

Method What It Does Example Result
.strip() Remove spaces from both ends " hello ".strip() "hello"
.lstrip() Remove spaces from left end only " hello ".lstrip() "hello "
.rstrip() Remove spaces from right end only " hello ".rstrip() " hello"

Examples:

messy_name = "  Alice  "
print(f"'{messy_name}'")  # '  Alice  '
clean_name = messy_name.strip()
print(f"'{clean_name}'")  # 'Alice'

Try it:

messy_name = " Alice " print(f"'{messy_name}'") # ' Alice ' clean_name = messy_name.strip() print(f"'{clean_name}'") # 'Alice'

Common use case: Cleaning user input

first_name = input("Enter your first name: ") # User types: " Bob " (with spaces)
surname = input("Enter your surname: ") # User types: " Sultana " (with spaces)
print(first_name + " " surname) # Output:  Bob  Sultana
# With strip(), " Bob " becomes "Bob" (spaces removed) and " Sultana " becomes "Sultana"
print(first_name.strip() + " " + surname.strip()) # Output: Bob Sultana

Checking String Content

Method What It Does Returns Example
.isdigit() Check if all characters are digits True or False "123".isdigit()True
.isalpha() Check if all characters are letters True or False "abc".isalpha()True
.isalnum() Check if all characters are letters or digits True or False "abc123".isalnum()True
.isspace() Check if all characters are whitespace True or False " ".isspace()True

Examples:

"123".isdigit()      # True
"12.5".isdigit()     # False (decimal point)
"abc".isdigit()      # False (letters)
"-5".isdigit()       # False (minus sign)

"hello".isalpha()    # True
"hello123".isalpha() # False (has numbers)
"hello ".isalpha()   # False (has space)

Try it:

"123".isdigit() # True print("12.5".isdigit()) # False (decimal point) print("abc".isdigit()) # False (letters) print("-5".isdigit()) # False (minus sign) print("hello".isalpha()) # True print("hello123".isalpha()) # False (has numbers) print("hello ".isalpha()) # False (has space)

Common use case: Validating input

age_input = input("Enter your age: ")

if age_input.isdigit():
    age = int(age_input)
    print(f"Your age: {age}")
else:
    print("Please enter only numbers!")

Finding and Replacing

Method What It Does Example Result
.startswith(text) Check if string starts with text "hello".startswith("he") True
.endswith(text) Check if string ends with text "hello".endswith("lo") True
.count(text) Count how many times text appears "hello".count("l") 2
.replace(old, new) Replace old text with new text "hello".replace("l", "r") "herro"

Examples:

filename = "report.pdf"
print(filename.endswith(".pdf"))  # True
print(filename.endswith(".doc"))  # False

sentence = "I love Python and Python is great"
print(sentence.count("Python"))  # 2

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

Try it:

"123".isdigit() # True filename = "report.pdf" print(filename.endswith(".pdf")) # True print(filename.endswith(".doc")) # False sentence = "I love Python and Python is great" print(sentence.count("Python")) # 2 message = "Hello World" new_message = message.replace("World", "Python") print(new_message) # Hello Python

Common use case: File extension checking

filename = input("Enter filename: ")

if filename.endswith(".py"):
    print("This is a Python file!")
elif filename.endswith(".txt"):
    print("This is a text file!")
else:
    print("Unknown file type")

Splitting and Joining

Method What It Does Example Result
.split() Split string into a list "a b c".split() ["a", "b", "c"]
.split(separator) Split by specific separator "a,b,c".split(",") ["a", "b", "c"]
separator.join(list) Join list items with separator "-".join(["a", "b"]) "a-b"

Examples:

# Split by spaces (default)
sentence = "Hello my friend"
words = sentence.split()
print(words)  # ["Hello", "my", "friend"]

# Split by comma
data = "apple,banana,orange"
fruits = data.split(",")
print(fruits)  # ["apple", "banana", "orange"]

# Join list into string
words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence)  # Python is fun

# Join with different separator
words = ["apple", "banana", "orange"]
result = ", ".join(words)
print(result)  # apple, banana, orange

Try it:

# Split by spaces (default) sentence = "Hello my friend" words = sentence.split() print(words) # ["Hello", "my", "friend"] # Split by comma data = "apple,banana,orange" fruits = data.split(",") print(fruits) # ["apple", "banana", "orange"] # Join list into string words = ["Python", "is", "fun"] sentence = " ".join(words) print(sentence) # Python is fun # Join with different separator words = ["apple", "banana", "orange"] result = ", ".join(words) print(result) # apple, banana, orange

Common use case: Processing comma-separated input

colors_input = input("Enter your favorite colors (comma-separated): ")
# User types: "red, blue, green"

colors = colors_input.split(",")
# Result: ["red", " blue", " green"]

# Clean up spaces
colors = [color.strip() for color in colors]
# Result: ["red", "blue", "green"]

Chaining Methods

You can chain multiple methods together:

messy_text = "  HELLO WORLD  "
clean_text = messy_text.strip().lower().capitalize()
print(clean_text)  # Hello world

# Step by step:
# 1. strip()      → "HELLO WORLD"
# 2. lower()      → "hello world"
# 3. capitalize() → "Hello world"

Try it:

messy_text = " HELLO WORLD " clean_text = messy_text.strip().lower().capitalize() print(clean_text) # Hello world

Common use case: Clean and normalize user input

answer = input("Continue? (yes/no): ").strip().lower()

if answer == "yes":
    print("Continuing...")
elif answer == "no":
    print("Stopping...")
else:
    print("Please enter yes or no")

Practical Examples

Example 1: Username Validation

username = input("Create username: ").strip()

if not username:
    print("Username cannot be empty!")
elif not username.isalnum():
    print("Username must be letters and numbers only!")
elif len(username) < 3:
    print("Username must be at least 3 characters!")
else:
    print(f"Username '{username}' created successfully!")

Example 2: Clean and Format Name

name = input("Enter your full name: ").strip().title()
print(f"Hello, {name}!")

# User types: "  alice SMITH  "
# Output: Hello, Alice Smith!

Example 3: Parse Email

email = input("Enter email: ").strip().lower()

if "@" not in email:
    print("Invalid email - missing @")
elif not email.endswith((".com", ".org", ".edu")):
    print("Invalid email - must end with .com, .org, or .edu")
else:
    username = email.split("@")[0]
    domain = email.split("@")[1]
    print(f"Username: {username}")
    print(f"Domain: {domain}")

Example 4: Count Words

sentence = input("Enter a sentence: ").strip()
words = sentence.split()
word_count = len(words)
print(f"Your sentence has {word_count} words")

Things to remember about strings

Strings are immutable:

name = "alice"
name.upper()      # Returns "ALICE" but doesn't change name
print(name)       # Still "alice"

# To save the change:
name = name.upper()
print(name)       # Now "ALICE"

Output:

alice
ALICE

Methods return new strings:

original = "hello"
modified = original.upper()

print(original)   # hello (unchanged)
print(modified)   # HELLO (new string)

Output:

hello
HELLO

Empty strings are falsy:

Empty strings are treated as absent strings, i.e. when you ask if the string is the case, False is returned:

text = ""
if text:
    print("Has content")
else:
    print("Empty!")  # This runs

gives the output: Output:

Empty!

By contrast, a string that contains a value would return True:

text = "hello"
if text:
    print("Has content") # This runs
else:
    print("Empty!")

gives the output:

Has content

Quick reference

  1. String methods transform or check strings
  2. Methods don’t change the original string - they return a new one
  3. Save the result if you want to keep changes: text = text.upper()
  4. Chain methods for multiple operations: .strip().lower()
  5. Use for validation - check user input before processing

Useful functions

Category Methods
Case .upper(), .lower(), .capitalize(), .title()
Whitespace .strip(), .lstrip(), .rstrip()
Check Type .isdigit(), .isalpha(), .isalnum(), .isspace()
Find .startswith(), .endswith(), .count()
Transform .replace(), .split(), .join()