🏠 Home
CPS Test Aim Trainer Typing Speed Scroll Speed View All Games →
AI Image Generator Background Remover Social Media Cropper Youtube Thumbnails View All Images →
Word Counter Case Converter Invisible Text Text to Speech View All Text Tools →
JSON Formatter Diff Checker Base64 Converter Meta Tag Generator View All Dev Tools →
Unit Converter Age Calculator BMI Calculator Time Zone Converter View All Calculators →
Home / Blog / Python String Methods

Python String Methods Quick Reference



Python code editor showing string method examples

Strings are one of Python's most used data types, and almost every script touches them: cleaning user input, parsing log lines, formatting output, and preprocessing text. Python strings are immutable, so every string method returns a new string rather than editing the original in place. Trying to change a single character by index raises an error; you rebind the variable instead.

This quick reference covers the methods you will actually reach for, with short examples and the pitfalls to watch for. Typically, a small handful of methods handle the majority of day-to-day text work, and the rest are there when you need them. All examples assume Python 3 and behave the same on Windows, macOS, and Linux. Under the hood, a string is a sequence of Unicode characters, so these methods work the same whether your text is plain English, symbols, or content pasted from another source.

Changing Case

Case methods return a copy with the letters adjusted: .upper() and .lower() are the workhorses, .title() title-cases each word, .swapcase() flips upper to lower and vice versa, and .capitalize() uppercases only the first character.

name = "python STRING"
name.upper()      # 'PYTHON STRING'
name.lower()      # 'python string'
name.title()      # 'Python String'
name.swapcase()   # 'PYTHON string'
name.capitalize() # 'Python string'

One trap: .title() treats apostrophes as word breaks, so "they're here".title() becomes "They'Re Here" — usually not what you want. For user-facing names, typically you will want .capitalize() applied to first and last names separately, or a small cleanup step after title-casing. For caseless comparisons — checking whether two usernames match no matter how they were typed — .casefold() is the safer choice because it is more aggressive than .lower() about Unicode.

Splitting and Joining

.split() breaks a string into a list. With no arguments it splits on any whitespace and ignores extra spaces. Pass a delimiter to split on that character: "a,b,c".split(",") gives ['a', 'b', 'c']. A second argument limits splits: "a,b,c,d".split(",", 2) stops after two splits, and .rsplit() starts from the right.

.splitlines() does the same job for line breaks, which is useful when processing files or pasted output line by line.

.join() is the inverse of split, but it is called on the separator, not the list:

"-".join(["2026", "12", "01"])   # '2026-12-01'
", ".join(["red", "green", "blue"])  # 'red, green, blue'

Note that .join() requires every item to be a string; numbers must be converted first, typically with a generator expression and str().

Use .partition(separator) when you only need the first split: it returns a 3-tuple of (before, separator, after), handy for parsing things like "user@domain.com". .rpartition() does the same from the right. A common real-world shape is splitting a log line with a limit: "2026-12-01 09:12 INFO request started".split(" ", 3) keeps the remainder of the line in the final element instead of breaking it apart.

Searching and Replacing

.find(substring) returns the index of the first match, or -1 when there is none. .index() works the same way but raises a ValueError on a miss, so use .find() when absence is a normal outcome. .count(substring) tallies non-overlapping occurrences.

.replace(old, new) replaces every occurrence unless you pass a third count argument to limit replacements. .startswith() and .endswith() return booleans and accept tuples, so you can check several prefixes or suffixes at once.

.rfind() and .rindex() search from the right, which is handy for file paths or URLs where the last separator is the one that matters.

"log.txt".endswith((".txt", ".log"))   # True
"apple banana apple".replace("apple", "orange", 1)  # 'orange banana apple'
Pro Tip: String methods chain cleanly because each one returns a string. " hello WORLD ".strip().title() becomes "Hello World". Keep chains short, though — long chains are hard to debug, and typically a clearly named intermediate variable reads better six months later.

Trimming and Padding

.strip() removes whitespace from both ends; .lstrip() and .rstrip() handle one side only. You can also pass a string of characters to strip instead of whitespace: "..hello..".strip(".") gives "hello".

Padding methods align text to a fixed width: .center(width), .ljust(width), .rjust(width), and .zfill(width), which zero-pads numbers on the left:

"7".zfill(3)     # '007'
"OK".center(10)  # '   OK   '

None of these truncate: if the string is already longer than the width, it comes back unchanged. .strip() only touches the ends — characters inside the string are never removed. This distinction matters most with fixed-width imports or user-entered values that carry accidental spaces.

Checking What a String Contains

Boolean check methods are useful for quick validation: .isdigit(), .isalpha(), .isalnum(), .isspace(), .islower(), .isupper(), and .istitle(). Each returns True or False. They are often a neat first gate before deeper parsing, though for anything mission-critical you will still want try/except around conversions like int() or float(), since .isdigit() does not catch negative numbers or decimals. "2026".isdigit() is True, while "-1".isdigit() is False.

Python String Methods FAQ

Are Python strings mutable?

No. Strings are immutable, so methods like .upper() or .replace() always return a new string and leave the original untouched. To "change" a variable, reassign the result: text = text.strip(). This is why methods never surprise you by altering data elsewhere in your program.

What is the difference between find() and index()?

Both locate a substring. .find() returns -1 when nothing matches, while .index() raises a ValueError. Use .find() when a missing substring is an expected case, and .index() when you want the program to fail loudly instead. Many programmers reach for .find() in if statements precisely because -1 is easy to test against.

Does strip() remove characters from the middle of a string?

No. .strip() only removes leading and trailing characters — whitespace by default, or whatever characters you pass in. Characters inside the string are never touched. If you need to remove characters from the middle, .replace(old, "") is the tool for that job.

Need to change text case without opening an editor? Try the free Case Converter — no signup, nothing uploaded.

Open Case Converter

Share This Article

⭐
Enjoying NoLoginTool?

Save it for later access 🚀