By WebNest Studio Engineering Team
Python Tutorial
Python String Methods Reference
Strings are the most used data type in almost every program — names, emails, messages, file contents, API responses. Python's str type comes with over 40 built-in methods for changing case, searching, testing content, splitting, joining, trimming, padding and replacing text.
This lesson is a complete, example-driven reference to the string methods, grouped by what they do. Remember that strings are immutable: every method returns a new string and leaves the original unchanged.
Why it matters
Most text processing does not need a regular expression. The built-in string methods can clean, search, split and test text, and knowing what is available saves you from writing loops for things that are one method call. Cleaning user input and parsing lines of a file are everyday uses.
Case Conversion
upper(), lower(), capitalize() (first character upper, rest lower), title() (each word capitalised), swapcase() and casefold() (an aggressive lowercase for case-insensitive comparison, handling characters like German "ß").
Searching and Counting
find(sub, start, end) returns the lowest index or -1; rfind() searches from the right. index() and rindex() do the same but raise ValueError when not found. count(sub) counts non-overlapping occurrences; startswith() and endswith() accept a string or a tuple of strings.
Testing Content (is... methods)
isalpha(), isdigit(), isdecimal(), isnumeric(), isalnum(), isspace(), islower(), isupper(), istitle(), isidentifier(), isprintable() and isascii() return True or False. isdecimal() accepts only 0–9 style digits, isdigit() also accepts superscripts, and isnumeric() also accepts characters like "½".
Splitting, Joining and Partitioning
split(sep, maxsplit) and rsplit() break a string into a list (no separator means "any whitespace"); splitlines() splits on line breaks; partition(sep) and rpartition(sep) return a 3-tuple (before, sep, after); sep.join(iterable) glues strings together.
Trimming, Padding and Alignment
strip(), lstrip(), rstrip() remove whitespace (or given characters); removeprefix() and removesuffix() remove an exact prefix/suffix. center(width, fill), ljust(), rjust() pad to a width; zfill(width) pads numbers with zeros; expandtabs(n) replaces tabs with spaces.
Replacing, Translating and Encoding
replace(old, new, count) replaces substrings; maketrans() + translate() replace or delete many single characters at once; encode(encoding) converts text to bytes (and bytes.decode() reverses it); format() and format_map() fill templates.
Examples
Case methods
s = "python PROGRAMMING is fun"
print(s.upper())
print(s.lower())
print(s.capitalize())
print(s.title())
print(s.swapcase())
print("Straße".casefold() == "STRASSE".casefold())
PYTHON PROGRAMMING IS FUN
python programming is fun
Python programming is fun
Python Programming Is Fun
PYTHON programming IS FUN
True
Searching and counting
text = "banana bandana"
print(text.find("an"), text.rfind("an"), text.find("xyz"))
print(text.index("band"))
print(text.count("an"), text.count("a", 0, 6))
print(text.startswith("ban"), text.endswith(("na", "xy")))
try:
text.index("xyz")
except ValueError as e:
print("ValueError:", e)
1 11 -1
7
4 3
True True
ValueError: substring not found
Testing content with is... methods
tests = ["Python", "2026", "abc123", " ", "Hello World", "user_name", "½", "²"]
for t in tests:
print(f"{t!r:14} alpha={t.isalpha()!s:5} decimal={t.isdecimal()!s:5} "
f"digit={t.isdigit()!s:5} numeric={t.isnumeric()!s:5} alnum={t.isalnum()!s:5} "
f"space={t.isspace()!s:5} title={t.istitle()!s:5} ident={t.isidentifier()}")
'Python' alpha=True decimal=False digit=False numeric=False alnum=True space=False title=True ident=True
'2026' alpha=False decimal=True digit=True numeric=True alnum=True space=False title=False ident=False
'abc123' alpha=False decimal=False digit=False numeric=False alnum=True space=False title=False ident=True
' ' alpha=False decimal=False digit=False numeric=False alnum=False space=True title=False ident=False
'Hello World' alpha=False decimal=False digit=False numeric=False alnum=False space=False title=True ident=False
'user_name' alpha=False decimal=False digit=False numeric=False alnum=False space=False title=False ident=True
'½' alpha=False decimal=False digit=False numeric=True alnum=True space=False title=False ident=False
'²' alpha=False decimal=False digit=True numeric=True alnum=True space=False title=False ident=False
split, rsplit, splitlines, partition, rpartition and join
csv = "asha,24,Pune,India"
print(csv.split(","))
print(csv.split(",", 1))
print(csv.rsplit(",", 1))
print(" many spaces here ".split())
print("line1\nline2\r\nline3".splitlines())
print("user@webnest.in".partition("@"))
print("archive.tar.gz".rpartition("."))
print(" | ".join(["Python", "Java", "SQL"]))
print("-".join("2026"))
['asha', '24', 'Pune', 'India']
['asha', '24,Pune,India']
['asha,24,Pune', 'India']
['many', 'spaces', 'here']
['line1', 'line2', 'line3']
('user', '@', 'webnest.in')
('archive.tar', '.', 'gz')
Python | Java | SQL
2-0-2-6
Trimming, prefixes, padding and alignment
raw = " hello world "
print(repr(raw.strip()), repr(raw.lstrip()), repr(raw.rstrip()))
print("xxhixx".strip("x"))
print("INV-1042".removeprefix("INV-"), "report.pdf".removesuffix(".pdf"))
print("[" + "Menu".center(12, "*") + "]")
print("[" + "Left".ljust(8) + "]", "[" + "Right".rjust(8) + "]")
print("42".zfill(5), "-42".zfill(5))
print(repr("a\tb".expandtabs(4)))
'hello world' 'hello world ' ' hello world'
hi
1042 report
[****Menu****]
[Left ] [ Right]
00042 -0042
'a b'
replace, translate, encode and format
msg = "I like Java. Java is great."
print(msg.replace("Java", "Python"))
print(msg.replace("Java", "Python", 1))
table = str.maketrans("aeiou", "AEIOU", "!?")
print("hello world!?".translate(table))
data = "₹500".encode("utf-8")
print(data, data.decode("utf-8"))
print("{} scored {:.1f}%".format("Asha", 91.456))
print("{name} is {age}".format_map({"name": "Ravi", "age": 30}))
print("Hello\tWorld".isprintable(), "abc".isascii(), "café".isascii())
I like Python. Python is great.
I like Python. Java is great.
hEllO wOrld
b'\xe2\x82\xb9500' ₹500
Asha scored 91.5%
Ravi is 30
False True False
Common Mistakes
- Calling s.upper() and expecting s to change — strings are immutable; assign the result.
- Using find() and forgetting it returns -1 (which is a valid negative index!) when not found.
- Using isdigit() to validate that text is a normal integer; isdecimal() is stricter, and int() in try/except is safest.
- Using strip("abc") expecting to remove the substring "abc" — it removes any of those characters; use removeprefix/removesuffix.
- Building strings in a loop with += instead of collecting parts and using join().
Exercise
Write a function that returns True if the text is a palindrome, ignoring upper and lower case and ignoring anything that is not a letter or a digit.
Expected output: True then False
def is_palindrome(text):
# TODO: keep only letters and digits, in lower case
# TODO: return whether the result reads the same in both directions
pass
print(is_palindrome("A man, a plan, a canal: Panama"))
print(is_palindrome("Python"))
Show hints
ch.isalnum()is true for letters and digits, andch.lower()gives the lower-case character.- Join the kept characters into a string and compare it with its reverse,
cleaned[::-1].
Show solution
def is_palindrome(text):
cleaned = "".join(ch.lower() for ch in text if ch.isalnum())
return cleaned == cleaned[::-1]
print(is_palindrome("A man, a plan, a canal: Panama"))
print(is_palindrome("Python"))
Quick quiz
1. What does "hello".find("z") return?
- A. None
- B. It raises ValueError
- C. 0
- D. -1
Show answer
D. find() returns -1 when the text is not found. index() raises ValueError in the same case.
2. What does "hello world".title() return?
- A. Hello World
- B. Hello world
- C. HELLO WORLD
- D. hello World
Show answer
A. title() capitalises the first letter of each word.
3. After name = " asha " and name.strip() on a line by itself, what is name?
- A. "asha"
- B. " asha "
- C. "asha "
- D. None
Show answer
B. String methods return a new string. The result must be assigned, as in name = name.strip().
Interview questions
What is the difference between find() and index()?
Show answer
Both return the position of the first occurrence of a substring. When the substring is not present, find() returns -1 and index() raises ValueError. To test only whether the text is present, the in operator is clearer than either.
What is the difference between split() and partition()?
Show answer
split(sep) breaks the string at every occurrence of the separator and returns a list of any length. partition(sep) breaks it at the first occurrence only and always returns three parts: the text before, the separator, and the text after. partition is convenient for a "key=value" line, since the result can always be unpacked into three names.
Key Points to Remember
- Every string method returns a new string; the original is unchanged.
- Case: upper, lower, capitalize, title, swapcase, casefold.
- Search: find/rfind (-1), index/rindex (ValueError), count, startswith, endswith.
- Tests: isalpha, isdigit, isdecimal, isnumeric, isalnum, isspace, istitle, isidentifier...
- split/rsplit/splitlines/partition break text; join combines; strip/pad/zfill/replace/translate transform it.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering