Skip to main content

Built-in String Methods

Python comes with helpful built-in tools called methods that let you clean up, inspect, or transform text quickly. You call a method by adding a dot . after the string variable name, followed by parentheses ().

:::important Strings Cannot Be Changed! Remember that Python strings are immutable (they cannot be modified in place). Every string method below returns a new copy of the text. It does not change the original variable unless you re-assign it. :::


1. Changing Case (Capitalization)

1.1 .upper() — Convert all letters to UPPERCASE

Converts every letter in a string to capital letters. Useful when you want to compare user codes or states in a consistent way.

name = "sai"
loud_name = name.upper()

print(loud_name) # Output: SAI
print(name) # Output: sai (original variable remains unchanged!)

1.2 .lower() — Convert all letters to lowercase

Converts every letter in a string to small letters. Commonly used to check emails or usernames since capitalization shouldn't matter (e.g., User@mail.com is same as user@mail.com).

email = "ThinkIT@Telugu.com"
clean_email = email.lower()

print(clean_email) # Output: thinkit@telugu.com

1.3 .title() — Convert to Title Case

Capitalizes the first letter of every word in a string, and makes all other letters lowercase. Perfect for formatting names of people or cities.

messy_name = "sRi saI rEsiDenCy"
nice_name = messy_name.title()

print(nice_name) # Output: Sri Sai Residency

2. Cleaning Text

2.1 .strip() — Remove leading & trailing whitespace

Removes all empty spaces, tabs, or newlines at the very beginning and the very end of a string. It does not remove spaces in the middle of words. Extremely useful for cleaning input fields in sign-up forms.

username = " sai_kumar_123 "
clean_username = username.strip()

print(f"Original: '{username}'")
print(f"Cleaned: '{clean_username}'")
# Output:
# Original: ' sai_kumar_123 '
# Cleaned: 'sai_kumar_123'

3. Searching & Swapping Text

3.1 .replace() — Swap old text with new text

Replaces all occurrences of a specific word or character with another word or character.

sentence = "I like Java programming."
new_sentence = sentence.replace("Java", "Python")

print(new_sentence) # Output: I like Python programming.

3.2 .find() — Locate where a word starts

Searches a string for a specific word or character and returns the position (index number) where it first appears. If Python cannot find the word, it returns -1.

message = "Welcome to Python Lab"

# Search for the word "Python"
position = message.find("Python")
print(position) # Output: 11 (P starts at index 11)

# Search for something that doesn't exist
missing = message.find("Java")
print(missing) # Output: -1

4. Splitting & Joining Text

4.1 .split() — Break a string into separate pieces

Chops a string into separate items based on a separator (like a space or comma) and returns a list.

:::info List Preview The .split() method returns a collection of items enclosed in square brackets [], which is called a List. We will learn all about Lists in the next module, but for now, think of it as a simple container holding separate words! :::

fruits_text = "apple,banana,grape"

# Split the text at each comma
fruit_list = fruits_text.split(",")
print(fruit_list) # Output: ['apple', 'banana', 'grape']

4.2 .join() — Glue separate pieces back together

Takes a list of words and glues them together into a single string, using a connector character between them.

words = ["Think", "IT", "Telugu"]

# Glue the words together with a space in between
sentence = " ".join(words)
print(sentence) # Output: Think IT Telugu

# Glue the words with a hyphen
dashed = "-".join(words)
print(dashed) # Output: Think-IT-Telugu

5. Checking Text Contents

These methods return either True or False (Boolean values), which are useful inside if statements.

5.1 .startswith() — Check if text begins with a word

sentence = "Python is awesome"

print(sentence.startswith("Python")) # Output: True
print(sentence.startswith("python")) # Output: False (Case-sensitive!)

5.2 .endswith() — Check if text ends with a word

Perfect for checking file types or extensions.

filename = "invoice.pdf"

if filename.endswith(".pdf"):
print("This is a PDF document.")
else:
print("Invalid file format.")

5.3 .isdigit() — Check if text contains only numbers

Returns True if the string contains only digit characters (0-9). Useful for validating phone numbers or pins before doing arithmetic.

pin = "1234"
age = "25 years"

print(pin.isdigit()) # Output: True
print(age.isdigit()) # Output: False (contains space and letters)

Common Mistakes to Avoid

Mistake: Expecting String Methods to Modify the Original Variable

Since strings cannot be changed in place, calling a method without storing the result does nothing to the original variable.

# Wrong - calling .upper() but not saving the result
text = "hello"
text.upper()
print(text) # Still outputs "hello"

# Right - reassign the result back to the variable
text = "hello"
text = text.upper()
print(text) # Outputs "HELLO"