String methods
Strings come with built-in methods — actions you can run on a string by writing a dot and the method name. They're perfect for cleaning up messy text.
Calling a method
Write the string (or a variable holding one), a dot, the method name, and parentheses:
Python
Four methods you'll use constantly
Python
.strip()removes whitespace from the start and end (not the middle)..lower()/.upper()change the case of every letter..replace(old, new)swaps every occurrence ofoldwithnew.
Strings are immutable
Methods never change the original string — they return a brand new one. The original stays exactly as it was:
Python
If you want to keep the result, you must store it in a variable (or use it right away). This catches almost every beginner.
Chaining methods
Because each method returns a string, you can call another method on the result:
Python
.strip() runs first, then .lower() runs on its result.
Key takeaways
- Call a method with
text.method(). .strip(),.lower(),.upper(), and.replace(old, new)are everyday cleaners.- Strings are immutable — methods return a new string; store it if you want to keep it.
- You can chain methods because each one returns a string.
No comments yet. Add the first comment to start the discussion.