Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • πŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • πŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • πŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • πŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • πŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • πŸ“ For Each Assignments
    • πŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • πŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • πŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • πŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • πŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • πŸ“ Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • πŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • πŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • πŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • πŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • πŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • πŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • πŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • πŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • πŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • πŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • πŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • πŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • πŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • πŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: String Methods

Python String Methods - Complete Guide

Master Python's powerful string methods β€” the tools you'll use every day.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • What Are String Methods?
  • Case Conversion Methods
  • Checking Methods (isalpha, isdigit, etc.)
  • Searching Methods (find, index, count)
  • Modifying Methods (replace, strip, split, join)
  • Alignment Methods (center, ljust, rjust)
  • Try It Yourself
  • Quick Quiz
  • Frequently Asked Questions
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • Case conversion β€” upper(), lower(), capitalize(), title()
  • Checking methods β€” isalpha(), isdigit(), isalnum(), isspace()
  • Searching methods β€” find(), index(), count(), startswith(), endswith()
  • Modifying methods β€” replace(), strip(), split(), join()
  • Alignment methods β€” center(), ljust(), rjust(), zfill()
  • Real-world examples β€” practical applications

What Are String Methods?

String methods are functions that belong to string objects. They let you do all kinds of things with text β€” change its case, search for patterns, split it into pieces, clean it up, and much more. Think of them as a Swiss Army knife for working with text.

Unlike operators, which are symbols like + and *, methods are called using dot notation. For example, instead of upper(text), you write text.upper(). This is because methods are attached to the string itself.

Here's the thing about string methods β€” they're immutable. That means they don't change the original string. Instead, they return a new string with the changes applied. This is a good thing because it makes your code more predictable and easier to debug.

πŸ’‘ Key concept: String methods are functions that belong to strings. They don't change the original string β€” they return a new one. This makes them safe and predictable to use.

Case Conversion Methods

1

Changing Letter Cases

# Python provides several methods to change the case of strings

text = "hello world"

# 1. upper() - convert to uppercase
print(text.upper())  # HELLO WORLD

# 2. lower() - convert to lowercase
text2 = "HELLO WORLD"
print(text2.lower())  # hello world

# 3. capitalize() - first letter uppercase, rest lowercase
text = "hello world"
print(text.capitalize())  # Hello world

# 4. title() - first letter of each word uppercase
text = "hello world"
print(text.title())  # Hello World

# 5. swapcase() - swap uppercase and lowercase
text = "Hello World"
print(text.swapcase())  # hELLO wORLD

# 6. casefold() - aggressive lowercasing (for case-insensitive comparisons)
text = "Straße"  # German
print(text.casefold())  # strasse

# 7. Practical: Converting user input to lowercase for comparison
user_input = "Yes"
if user_input.lower() == "yes":
    print("User said yes")

Case methods summary:

  • upper() β€” all characters to uppercase
  • lower() β€” all characters to lowercase
  • capitalize() β€” first letter uppercase
  • title() β€” first letter of each word uppercase
  • swapcase() β€” swaps case of each character
  • casefold() β€” aggressive lowercasing for comparison

Quick Check: Which method converts the first letter of each word to uppercase? (Answer: title())

Checking Methods (isalpha, isdigit, etc.)

2

Checking What's Inside a String

# Checking methods return True or False

# 1. isalpha() - all characters are letters
print("Hello".isalpha())    # True
print("Hello123".isalpha()) # False
print("".isalpha())         # False

# 2. isdigit() - all characters are digits
print("123".isdigit())    # True
print("123a".isdigit())   # False
print("".isdigit())       # False

# 3. isalnum() - all characters are letters or digits
print("Hello123".isalnum()) # True
print("Hello 123".isalnum()) # False (space)
print("".isalnum())         # False

# 4. isspace() - all characters are whitespace
print("   ".isspace())   # True
print(" a ".isspace())   # False
print("".isspace())      # False

# 5. isupper() - all characters are uppercase
print("HELLO".isupper()) # True
print("Hello".isupper()) # False

# 6. islower() - all characters are lowercase
print("hello".islower()) # True
print("Hello".islower()) # False

# 7. istitle() - string is titlecased (each word starts with uppercase)
print("Hello World".istitle()) # True
print("Hello world".istitle()) # False

# 8. Practical: Validating user input
username = input("Enter username (letters only): ")
if username.isalpha():
    print("Valid username")
else:
    print("Username can only contain letters")

Checking methods summary:

  • isalpha() β€” letters only
  • isdigit() β€” digits only
  • isalnum() β€” letters or digits
  • isspace() β€” whitespace only
  • isupper() β€” all uppercase
  • islower() β€” all lowercase
  • istitle() β€” title case

Quick Check: Which method checks if a string contains only digits? (Answer: isdigit())

Searching Methods (find, index, count)

3

Finding Things in Strings

# Searching methods help you find substrings

text = "Python is amazing. Python is powerful."

# 1. find() - returns first index or -1 if not found
print(text.find("Python"))   # 0
print(text.find("Java"))     # -1
print(text.find("is"))       # 7

# 2. find() with start and end
print(text.find("Python", 10))  # 21 (search from index 10)

# 3. rfind() - returns last index or -1 if not found
print(text.rfind("Python"))  # 21

# 4. index() - like find(), but raises ValueError if not found
print(text.index("Python"))  # 0
# print(text.index("Java"))  # ValueError

# 5. count() - count occurrences
print(text.count("Python"))  # 2
print(text.count("is"))      # 2

# 6. startswith() - check if string starts with a prefix
print(text.startswith("Python"))  # True
print(text.startswith("Java"))    # False

# 7. endswith() - check if string ends with a suffix
text2 = "hello.txt"
print(text2.endswith(".txt"))  # True
print(text2.endswith(".pdf"))  # False

# 8. Practical: Finding file extensions
filename = "document.pdf"
if filename.endswith(".pdf"):
    print("This is a PDF file")

# 9. Practical: Extracting username from email
email = "user@example.com"
at_index = email.find("@")
username = email[:at_index]
print(f"Username: {username}")

Searching methods summary:

  • find() β€” returns index or -1
  • index() β€” returns index or raises error
  • rfind() β€” finds from the right
  • count() β€” counts occurrences
  • startswith() β€” checks prefix
  • endswith() β€” checks suffix

Quick Check: What's the difference between find() and index()? (Answer: find() returns -1 if not found, index() raises ValueError)

Modifying Methods (replace, strip, split, join)

4

Changing and Cleaning Strings

# These methods modify strings in various ways

# 1. replace() - replace occurrences of a substring
text = "Hello World"
print(text.replace("World", "Python"))  # Hello Python
print(text.replace("l", "L"))           # HeLLo WorLd

# replace() with count
text = "aaa bbb aaa"
print(text.replace("a", "x", 2))  # xxa bbb aaa (only first 2)

# 2. strip() - remove whitespace from both ends
text = "  Hello  "
print(text.strip())    # "Hello"
print(text.lstrip())   # "Hello  " (only left)
print(text.rstrip())   # "  Hello" (only right)

# 3. strip() with custom characters
text = "!!!Hello!!!"
print(text.strip("!"))  # Hello

# 4. split() - split string into a list
text = "apple,banana,cherry"
print(text.split(","))  # ['apple', 'banana', 'cherry']
print(text.split())     # ['apple,banana,cherry']

# 5. split() with max splits
text = "one,two,three,four"
print(text.split(",", 2))  # ['one', 'two', 'three,four']

# 6. join() - join a list into a string
words = ["apple", "banana", "cherry"]
print(", ".join(words))  # apple, banana, cherry

# 7. Practical: Cleaning user input
user_input = "  Hello  "
cleaned = user_input.strip()
print(f"'{cleaned}'")  # 'Hello'

# 8. Practical: Parsing CSV data
csv_line = "Alice,25,Engineer"
parts = csv_line.split(",")
print(f"Name: {parts[0]}, Age: {parts[1]}, Job: {parts[2]}")

Modifying methods summary:

  • replace() β€” replaces substrings
  • strip() β€” removes whitespace from ends
  • lstrip() β€” removes from left only
  • rstrip() β€” removes from right only
  • split() β€” splits into a list
  • join() β€” joins a list into a string

Quick Check: What method removes whitespace from both ends of a string? (Answer: strip())

Alignment Methods (center, ljust, rjust)

5

Positioning Text

# These methods help you align text

# 1. center() - center align with padding
text = "Hello"
print(text.center(10))   # "  Hello   "
print(text.center(10, "*")) # "**Hello***"

# 2. ljust() - left align with padding
text = "Hello"
print(text.ljust(10))    # "Hello     "
print(text.ljust(10, "-")) # "Hello-----"

# 3. rjust() - right align with padding
text = "Hello"
print(text.rjust(10))    # "     Hello"
print(text.rjust(10, "-")) # "-----Hello"

# 4. zfill() - pad with zeros on the left
number = "42"
print(number.zfill(5))   # "00042"

# 5. Practical: Creating a table
def create_table_row(text, width=20):
    return "| " + text.ljust(width - 2) + " |"

print(create_table_row("Name"))
print(create_table_row("Age"))
print(create_table_row("City"))

# 6. Practical: Progress display
def format_progress(percent):
    return f"[{str(percent).rjust(3)}%]"

print(format_progress(5))   # "[  5%]"
print(format_progress(100)) # "[100%]"

# 7. Creating a nice header
header = "WELCOME"
print(header.center(40, "="))
# "===============WELCOME================"

Alignment methods summary:

  • center() β€” center aligns the string
  • ljust() β€” left aligns the string
  • rjust() β€” right aligns the string
  • zfill() β€” pads with zeros

Quick Check: Which method would you use to pad a number with zeros? (Answer: zfill())

Try It Yourself

Experiment with string methods in the editor below.

Loading Pyodide... 0%
Python Code Editor
========================================
STRING METHODS PRACTICE
========================================

1. CASE CONVERSION
Upper: ' HELLO WORLD '
Lower: ' hello world '
Title: ' Hello World '
Capitalize: ' hello world '

2. CHECKING METHODS
Is alpha: True
Is digit: True
Is alnum: True

3. SEARCHING METHODS
Find 'Python': 0
Count 'Python': 2
Starts with 'Python': True

4. MODIFYING METHODS
Strip: 'hello world'
Replace: ' hi world '
Split: ['hello', 'world']

5. ALIGNMENT METHODS
Center: '** hello world **'
Left: ' hello world '
Right: ' hello world '

String methods practice complete!
πŸ†

You've Got It!

You now know Python's most important string methods. From case conversion to searching, cleaning, and alignment β€” you have the tools to work with text effectively.

Quick Quiz

Test what you've learned:

1. Which method converts a string to uppercase?
2. Which method checks if a string contains only letters?
3. What does strip() do?
4. Which method splits a string into a list?
5. What is the difference between find() and index()?

Frequently Asked Questions

What is the difference between upper() and capitalize()? β–Ό

upper() converts all characters to uppercase (e.g., "hello" β†’ "HELLO"). capitalize() only converts the first character to uppercase and the rest to lowercase (e.g., "hello" β†’ "Hello").

What is the difference between strip() and replace()? β–Ό

strip() only removes whitespace (or specified characters) from the beginning and end of a string. replace() can replace any substring anywhere in the string with another substring.

What's a common interview question about string methods? β–Ό

Common questions include: "How do you remove whitespace from a string?" "How do you check if a string contains only digits?" and "What is the difference between find() and index()?"

Do string methods change the original string? β–Ό

No, strings are immutable. All string methods return a new string with the changes applied. The original string remains unchanged. This is why you often see text = text.upper() β€” you're assigning the new string back to the variable.

When should I use isdigit() vs isnumeric()? β–Ό

isdigit() checks if all characters are digits (0-9). isnumeric() checks if all characters are numeric, which includes digits, fractions, and other numeric characters (like Β½). For most cases, isdigit() is what you need.

How do I join a list of strings? β–Ό

Use the join() method on the separator string: ", ".join(["apple", "banana", "cherry"]) gives "apple, banana, cherry". The separator is the string you call join() on.

Where to Go From Here

Now that you've mastered string methods, check out these related topics:

πŸ“ Assignments

Practice what you've learned with assignments.

Learn More β†’

Regular Expressions

Learn advanced pattern matching with regex.

Learn More β†’

Object-Oriented Programming

Learn about classes and objects in Python.

Learn More β†’
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
  • Python Lists and Dictionaries Interview Questions
  • Python OOP Interview Questions
  • SQL Set Operators Interview Questions
Previous: String Formatting Operators Next: πŸ“ Assignments β†’