Python Variable & Data Type
Python String Methods
Learn Python String Methods with clear explanations, Python examples, and practical programming guidance.
What are Python string methods?
String methods are operations provided by Python's built-in str type. They help you search, validate, split, format, and transform text. Strings are immutable, so these methods return a new value and leave the original string unchanged.
Case-conversion methods
| Method | Purpose | Example result |
|---|---|---|
upper() | Converts letters to uppercase. | "python".upper() → "PYTHON" |
lower() | Converts letters to lowercase. | "PYTHON".lower() → "python" |
title() | Capitalizes the first letter of each word. | "learn python".title() |
capitalize() | Capitalizes the first character only. | "python".capitalize() |
swapcase() | Switches uppercase letters to lowercase and vice versa. | "PyThOn".swapcase() |
casefold() | Performs stronger lowercase conversion for case-insensitive comparisons. | "Python".casefold() |
text = "i love learning python"
print(text.upper())
print(text.lower())
print(text.title())
print(text.capitalize())
print("PyThOn".swapcase())Each call creates a result; text itself is not changed.
Searching and finding text
| Method | Behavior when text is found | Behavior when text is missing |
|---|---|---|
find(sub) | Returns the first index. | Returns -1. |
index(sub) | Returns the first index. | Raises ValueError. |
rfind(sub) | Returns the last index. | Returns -1. |
rindex(sub) | Returns the last index. | Raises ValueError. |
count(sub) | Counts non-overlapping occurrences. | Returns 0. |
startswith(prefix) | Returns True when the string begins with the prefix. | |
endswith(suffix) | Returns True when the string ends with the suffix. | |
text = "Python programming with Python"
print(text.find("Python"))
print(text.rfind("Python"))
print(text.count("Python"))
print(text.startswith("Python"))
print(text.endswith("Python"))
print(text.find("Java"))25
2
True
True
-1
Use find() when a missing substring is expected. Use index() only when a missing value represents an error that should be handled.
Splitting and joining strings
| Method | Purpose |
|---|---|
split(separator, maxsplit) | Splits from the left and returns a list. |
rsplit(separator, maxsplit) | Splits from the right and returns a list. |
splitlines() | Splits text at line boundaries. |
partition(separator) | Returns a three-item tuple: before, separator, and after. |
rpartition(separator) | Performs partitioning from the right. |
separator.join(iterable) | Combines strings using the separator. |
text = "Learning Python is practical"
print(text.split())
print(text.rsplit(" ", 2))
print(text.partition("Python"))
print(", ".join(["Python", "Java", "SQL"]))The values passed to join() must be strings. Convert numeric values before joining them.
Removing and replacing text
| Method | Purpose |
|---|---|
strip(chars) | Removes matching characters from both ends; whitespace is removed when no argument is supplied. |
lstrip(chars) | Removes matching characters from the left. |
rstrip(chars) | Removes matching characters from the right. |
replace(old, new, count) | Returns a copy with selected occurrences replaced. |
removeprefix(prefix) | Removes a prefix when it is present. |
removesuffix(suffix) | Removes a suffix when it is present. |
text = " Python programming "
print(text.strip())
print(text.lstrip())
print(text.rstrip())
print(text.replace("programming", "development"))
print("Python: ".removeprefix("Python: "))
print("notes.txt".removesuffix(".txt"))The chars argument in strip() is a set of characters, not a complete substring. Use removeprefix() or removesuffix() when removing an exact prefix or suffix.
String validation methods
| Method | Returns True when... |
|---|---|
isalpha() | All characters are alphabetic and the string is not empty. |
isdigit() | All characters are digits. |
isdecimal() | All characters are decimal characters. |
isalnum() | All characters are alphabetic or numeric. |
isspace() | All characters are whitespace. |
islower() / isupper() | All cased characters use the requested case. |
istitle() | The string follows title-case rules. |
isidentifier() | The text is a valid Python identifier. |
isascii() | All characters are ASCII characters. |
values = ["Welcome", "PYTHON", "123", "Python3", " "]
for value in values:
print(value, value.isalpha(), value.isdigit(), value.isalnum(), value.isspace())Validation methods are useful for checking simple input rules, but more complex formats such as email addresses usually need dedicated validation logic.
Alignment and formatting methods
| Method | Purpose |
|---|---|
center(width, fillchar) | Centers text within a field. |
ljust(width, fillchar) | Aligns text to the left. |
rjust(width, fillchar) | Aligns text to the right. |
zfill(width) | Adds zeros to the left, preserving a sign when present. |
format() and f-strings | Insert values and apply formatting rules. |
text = "Python"
print(text.ljust(10, "-"))
print(text.rjust(10, "-"))
print(text.center(10, "-"))
print("1243".zfill(6))
name = "Asha"
score = 91.456
print(f"{name} scored {score:.2f}")----Python
--Python--
001243
Asha scored 91.46
Encoding and decoding
encode() converts a string to bytes using an encoding such as UTF-8. The corresponding decode() method converts those bytes back to a string:
text = "café"
encoded = text.encode("utf-8")
decoded = encoded.decode("utf-8")
print(encoded)
print(decoded)Use the same compatible encoding when encoding and decoding. UTF-8 is a common choice because it supports a wide range of Unicode characters.
Additional useful string methods
expandtabs(tabsize)replaces tab characters with spaces.translate(table)replaces characters according to a translation table.maketrans()creates a translation table fortranslate().format_map(mapping)formats a string using a mapping of names to values.isprintable()checks whether all characters can be displayed.isnumeric()checks for Unicode numeric characters.
Best practices
- Remember that string methods return new strings; assign the result when you need to keep it.
- Use
join()for combining many strings efficiently. - Use
find()when a missing value is valid andindex()when it should be an error. - Use
casefold()for robust case-insensitive comparisons across languages. - Use explicit encodings when reading and writing files.
- Validate user input before using it in a business rule or database query.
Further Reading
Continue learning with these related Python tutorials:
Continue learning
