Cyber Services / All lessons / Python Programming / Python String Methods

Python String Methods

Module 29 of 31 · 3 min read · Free to read

MODULES ↓ Command blocks have a COPY button

Hey coder! Let's dive into some awesome Python string methods. These are like special tools to manipulate text. You can copy and paste the code snippets directly into a Python interpreter to see them in action!

Meet Our Sample String

# Define our sample string
txt = "  SanDeW python session in progress a python        "

String Method Showcase

Here's a breakdown of each method, using our sample string:

len()
Counts all characters (including spaces!) in a string.
# Calculate and print the length
length = len(txt)
print("Length => ", length)  # Output: 51
.upper()
Converts the entire string to uppercase.
# Convert to uppercase and print
up = txt.upper()
print("Upper Case=>", up)  # Output: SANDEW PYTHON SESSION...
.lower()
Converts the entire string to lowercase.
# Convert to lowercase and print
lo = txt.lower()
print("Lower Case=>", lo)  # Output: sandew python session...
.capitalize()
Capitalizes only the first letter of the string.
# Capitalize the first letter and print
output = "SanDeW PYthon session...".capitalize()
print("Captalize=>", output)  # Output: Sandew python session...
.strip()
Removes extra spaces from beginning and end of string.
# Strip whitespace and print
st = txt.strip()
print(st, " strip= Length ", len(txt.strip()))  # Output: SanDeW python... Length 47
.lstrip() & .rstrip()
Removes spaces only from left or right side.
# Left strip whitespace
print("lstrip Length:", len(txt.lstrip()))  # Output: 49

# Right strip whitespace  
print("rstrip Length:", len(txt.rstrip()))  # Output: 47
.replace()
Replaces one character (or substring) with another.
# Replace characters and print
rep = txt.replace('e','3')
print("Replace= ", rep)  # Output: SanD3W python s3ssion...
.find() & .rfind()
Finds first/last occurrence of substring (returns -1 if not found).
# Find first occurrence
print("find=>", txt.find("python"))  # Output: 9

# Find last occurrence
print("Rfind=>", txt.rfind("python"))  # Output: 38
.index() & .rindex()
Like find/rfind but raises exception if substring not found.
# Find first index
print("Index=>", txt.index("a"))  # Output: 3

# Find last index
print("RIndex=>", txt.rindex("a"))  # Output: 40
.startswith() & .endswith()
Checks if string starts/ends with specific substring (True/False).
# Check start
print("Startswith =>", txt.startswith("  San1"))  # Output: False

# Check end
print("endswith =>", txt.endswith("  "))  # Output: True
.count()
Counts how many times a substring appears in the string.
# Count occurrences
count = txt.count("s")
print("Count=>", count)  # Output: 5
.split() & .rsplit()
Breaks string into list of substrings (default separator is space).
# Split string
print("Split=>", txt.split(" "))

# Right split
print("RSplit=>", txt.rsplit("s"))
.title()
Capitalizes first letter of each word in the string.
# Show title case
print("Title=>", txt.title())  # Output: Sandew Python Session...
.swapcase()
Swaps uppercase letters to lowercase and vice versa.
# Show swap case
print("Swap Case=>", txt.swapcase())  # Output: sANdEw PYTHON SESSION...
.isalnum(), .isalpha(), .isdigit()
Checks if all characters are alphanumeric, alphabetic, or digits.
# Alphanumeric check
print("Alphanumeric?", txt.isalnum())  # Output: False

# Alpha check
print("Alpha?", "Sandew".isalpha())  # Output: True

# Digit check
print("Digit?", "12345".isdigit())  # Output: True
.islower(), .isupper(), .istitle()
Checks if all characters are lowercase, uppercase, or title case.
# Lowercase check
print("Lower?", "sandew".islower())  # Output: True

# Uppercase check
print("Upper?", "SANDEW".isupper())  # Output: True

# Title case check
print("Title?", "My Favourite Country".istitle())  # Output: True
Modules (31) ← Python Programming