Python String Methods

Hey! Let's learn how to easily play with text in Python. From cleaning up messy input to searching for words, these methods are your best friends.

The Golden Rule: Immutability

In Python, strings are "immutable." This sounds fancy, but it just means you can't change the original text. Instead, these methods create a new version of your text with the changes applied.

Cleaning Up Text

  • strip(): Removes extra spaces from start/end.
  • upper() / lower(): Changes everything to big or small letters.
  • replace('old', 'new'): Swaps out parts of your text.

Asking Python Questions

isalpha()
Only letters?
isalnum()
Letters or numbers?
startswith()
Starts with this?
isspace()
Just empty space?

Finding Things

Need to find where a word is hiding? Use find() or index().

text = "Hello Python"
print(text.find("Python")) # Output: 6
print(text.find("Java")) # Output: -1 (Safe!)

* Pro tip: Always use find() because if it can't find the word, it gives you -1 instead of crashing your program!