Python string methods are built-in functions that allow you to manipulate and analyze strings. These methods do not modify the original string but return a new string with the changes applied.
Core String Methods Overview
Case Manipulation:
capitalize(): Converts the first character to uppercase and the rest to lowercase.upper(): Converts all characters to uppercase.lower(): Converts all characters to lowercase.swapcase(): Swaps uppercase to lowercase and vice versa.title(): Capitalizes the first letter of each word.
Search and Find:
find(sub[, start[, end]]): Returns the lowest index where substringsubis found; returns-1if not found.rfind(sub[, start[, end]]): Returns the highest index where substringsubis found.index(sub[, start[, end]]): Similar tofind(), but raises aValueErrorif not found.count(sub[, start[, end]]): Returns the number of non-overlapping occurrences ofsub.
Check Conditions:
isalpha(): ReturnsTrueif all characters are alphabetic.isdigit(): ReturnsTrueif all characters are digits.isalnum(): ReturnsTrueif all characters are alphanumeric.isspace(): ReturnsTrueif all characters are whitespace.isupper(),islower(),istitle(): Check case conditions.isidentifier(): Checks if the string is a valid Python identifier.
Trim and Align:
strip(): Removes leading and trailing whitespace.lstrip(),rstrip(): Remove only leading or trailing whitespace.center(width[, fillchar]): Centers the string in a field of given width.ljust(width[, fillchar]),rjust(width[, fillchar]): Left- or right-align the string.
Split and Join:
split(sep=None): Splits the string into a list usingsepas the delimiter.rsplit(sep=None): Splits from the right.splitlines(): Splits the string at line boundaries.join(iterable): Joins elements of an iterable with the string as a separator.
Replace and Format:
replace(old, new[, count]): Replaces occurrences ofoldwithnew.format(*args, **kwargs): Formats the string using placeholders.format_map(mapping): Formats using a dictionary.
Check Prefix/Suffix:
startswith(prefix[, start[, end]]): ReturnsTrueif the string starts withprefix.endswith(suffix[, start[, end]]): ReturnsTrueif the string ends withsuffix.
Other Useful Methods:
encode(): Encodes the string using a specified encoding.expandtabs(tabsize=8): Replaces tab characters with spaces.maketrans(x[, y[, z]]): Returns a translation table for use withtranslate().translate(table): Translates characters using a mapping table.zfill(width): Pads the string with zeros on the left to fill a width.
For full details and examples, refer to the official Python documentation on string methods.