Python String Methods
Python provides a rich set of methods for string manipulation. This guide covers the most commonly used string methods, their syntax, and practical examples.
Case Modification
-
upper(): Converts all characters to uppercase"hello".upper() # "HELLO" -
lower(): Converts all characters to lowercase"WORLD".lower() # "world" -
capitalize(): Capitalizes the first character"python".capitalize() # "Python" -
title(): Converts the first character of each word to uppercase"hello world".title() # "Hello World" -
swapcase(): Swaps case for all characters"PyThOn".swapcase() # "pYtHoN"
Searching and Replacing
-
find(sub[, start[, end]]): Returns the lowest index of substring"Hello".find("l") # 2 -
rfind(sub[, start[, end]]): Returns the highest index of substring"Hello".rfind("l") # 3 -
index(sub[, start[, end]]): Like find(), but raises ValueError when not found"Hello".index("o") # 4 -
rindex(sub[, start[, end]]): Like rfind(), but raises ValueError when not found"Hello".rindex("l") # 3 -
replace(old, new[, count]): Replaces occurrences of a substring"Hello".replace("l", "L") # "HeLLo"
Checking String Content
-
startswith(prefix[, start[, end]]): Checks if string starts with the specified prefix"Python".startswith("Py") # True -
endswith(suffix[, start[, end]]): Checks if string ends with the specified suffix"Python".endswith("on") # True -
isalpha(): Checks if all characters are alphabetic"Python".isalpha() # True
"Python3".isalpha() # False -
isalnum(): Checks if all characters are alphanumeric"Python3".isalnum() # True -
isdigit(): Checks if all characters are digits"123".isdigit() # True -
isspace(): Checks if all characters are whitespace" ".isspace() # True
Stripping and Splitting
-
strip([chars]): Removes leading and trailing characters (default: whitespace)" Python ".strip() # "Python" -
lstrip([chars]): Removes leading characters (default: whitespace)" Python".lstrip() # "Python" -
rstrip([chars]): Removes trailing characters (default: whitespace)"Python ".rstrip() # "Python" -
split([sep[, maxsplit]]): Splits the string into a list"Hello,World".split(",") # ["Hello", "World"] -
rsplit([sep[, maxsplit]]): Splits the string from the right"a,b,c,d".rsplit(",", 2) # ['a,b', 'c', 'd'] -
splitlines([keepends]): Splits the string at line breaks"Hello\nWorld".splitlines() # ["Hello", "World"]
Joining and Formatting
-
join(iterable): Joins elements of an iterable using the string as separator",".join(["a", "b", "c"]) # "a,b,c" -
format(*args, **kwargs): Formats the string"{} {}".format("Hello", "World") # "Hello World" -
center(width[, fillchar]): Centers string within width"Python".center(10, "-") # "--Python--" -
ljust(width[, fillchar]): Left-justifies string within width"Python".ljust(10, "-") # "Python----" -
rjust(width[, fillchar]): Right-justifies string within width"Python".rjust(10, "-") # "----Python" -
zfill(width): Pads string on the left with zeros"42".zfill(5) # "00042"
Encoding and Decoding
-
encode([encoding[, errors]]): Returns encoded version of the string"Pythön".encode("utf-8") # b'Pyth\xc3\xb6n' -
decode([encoding[, errors]]): Decodes the string using the codec registered for encodingb'Pyth\xc3\xb6n'.decode("utf-8") # "Pythön"
Miscellaneous
-
count(sub[, start[, end]]): Counts non-overlapping occurrences of substring"Mississippi".count("ss") # 2 -
expandtabs([tabsize]): Expands tabs in string to spaces"a\tb\tc".expandtabs(4) # "a b c" -
maketrans(x[, y[, z]]): Returns a translation table usable for translate()trans = str.maketrans("aeiou", "12345")
"hello".translate(trans) # "h2ll4"
These string methods provide powerful tools for string manipulation in Python. Understanding and effectively using these methods can significantly enhance your text processing capabilities.