String Methods in Python
String Methods in Python
Python provides a wide variety of built-in string methods to manipulate, search, and modify string values. Below is a list of common string methods and their descriptions.
1. Case Methods
lower(): Converts all characters in the string to lowercase.s = "HELLO"print(s.lower()) # Output: "hello"upper(): Converts all characters in the string to uppercase.s = "hello"print(s.upper()) # Output: "HELLO"capitalize(): Capitalizes the first character of the string and makes all other characters lowercase.s = "hello world"print(s.capitalize()) # Output: "Hello world"title(): Capitalizes the first character of each word.s = "hello world"print(s.title()) # Output: "Hello World"swapcase(): Swaps the case of each character (lowercase becomes uppercase and vice versa).s = "Hello World"print(s.swapcase()) # Output: "hELLO wORLD"casefold(): Similar tolower(), but it’s more aggressive and designed for case-insensitive comparisons (especially useful for comparisons involving non-English characters).s = "HELLO"print(s.casefold()) # Output: "hello"
2. Searching Methods
find(sub): Returns the index of the first occurrence ofsubin the string. Returns-1ifsubis not found.s = "hello world"print(s.find("world")) # Output: 6print(s.find("Python")) # Output: -1rfind(sub): Returns the index of the last occurrence ofsubin the string. Returns-1ifsubis not found.s = "hello world, hello"print(s.rfind("hello")) # Output: 13index(sub): Similar tofind(), but raises aValueErrorifsubis not found.s = "hello world"print(s.index("world")) # Output: 6# print(s.index("Python")) # Raises ValueErrorcount(sub): Returns the number of occurrences ofsubin the string.s = "hello hello world"print(s.count("hello")) # Output: 2startswith(prefix): ReturnsTrueif the string starts withprefix, otherwiseFalse.s = "hello world"print(s.startswith("hello")) # Output: Trueendswith(suffix): ReturnsTrueif the string ends withsuffix, otherwiseFalse.s = "hello world"print(s.endswith("world")) # Output: True
3. Trimming Methods
strip(): Removes leading and trailing whitespace characters (spaces, tabs, newlines).s = " hello "print(s.strip()) # Output: "hello"lstrip(): Removes leading whitespace characters.s = " hello"print(s.lstrip()) # Output: "hello"rstrip(): Removes trailing whitespace characters.s = "hello "print(s.rstrip()) # Output: "hello"
4. Modification Methods
replace(old, new): Replaces all occurrences ofoldwithnewin the string.s = "hello world"print(s.replace("world", "Python")) # Output: "hello Python"split(sep): Splits the string into a list of substrings based on the separatorsep. If no separator is provided, it splits by any whitespace.s = "hello world"print(s.split()) # Output: ['hello', 'world']s = "apple,banana,orange"print(s.split(',')) # Output: ['apple', 'banana', 'orange']join(iterable): Joins elements of an iterable (like a list) into a string, using the string as the separator.words = ["hello", "world"]print(" ".join(words)) # Output: "hello world"zfill(width): Pads the string with zeroes from the left until the string reaches the specified width.s = "42"print(s.zfill(5)) # Output: "00042"rjust(width): Aligns the string to the right by padding it with spaces (or other characters) until it reaches the specified width.s = "hello"print(s.rjust(10)) # Output: " hello"ljust(width): Aligns the string to the left by padding it with spaces (or other characters) until it reaches the specified width.s = "hello"print(s.ljust(10)) # Output: "hello "
5. String Alignment Methods
center(width): Centers the string within a field of the specified width by padding it with spaces.s = "hello"print(s.center(10)) # Output: " hello "expandtabs(tabsize): Replaces all tab characters (\t) with spaces, consideringtabsizeas the number of spaces per tab.s = "hello\tworld"print(s.expandtabs(4)) # Output: "hello world"
6. Testing Methods
isalnum(): ReturnsTrueif all characters in the string are alphanumeric (letters or numbers).s = "hello123"print(s.isalnum()) # Output: Trueisalpha(): ReturnsTrueif all characters in the string are alphabetic (letters).s = "hello"print(s.isalpha()) # Output: Trueisdigit(): ReturnsTrueif all characters in the string are digits.s = "12345"print(s.isdigit()) # Output: Trueisspace(): ReturnsTrueif all characters in the string are whitespace.s = " "print(s.isspace()) # Output: Trueistitle(): ReturnsTrueif the string is in title case (first letter of each word is capitalized).s = "Hello World"print(s.istitle()) # Output: Trueisupper(): ReturnsTrueif all characters in the string are uppercase.s = "HELLO"print(s.isupper()) # Output: Trueislower(): ReturnsTrueif all characters in the string are lowercase.s = "hello"print(s.islower()) # Output: True
7. Encoding and Decoding Methods
encode(encoding): Returns an encoded version of the string as bytes, using the specified encoding.s = "hello"encoded = s.encode("utf-8")print(encoded) # Output: b'hello'decode(encoding): Converts an encoded byte object back into a string using the specified encoding.encoded = b'hello'decoded = encoded.decode("utf-8")print(decoded) # Output: "hello"
Conclusion
These are some of the most commonly used string methods in Python. They allow you to perform a wide range of tasks such as searching, modifying, trimming, and formatting strings. Understanding and using these methods will help you work efficiently with strings in Python.