Python String Methods
Python provides a rich set of string methods for manipulating and processing string data. These methods can perform tasks such as searching, modifying, formatting, and analyzing strings. Here’s a comprehensive overview of the most commonly used Python string methods:
1. Case-Related Methods
lower(): Converts all characters in a string to lowercase."HELLO".lower() # Output: "hello"upper(): Converts all characters in a string to uppercase."hello".upper() # Output: "HELLO"capitalize(): Converts the first character of the string to uppercase and the rest to lowercase."hello world".capitalize() # Output: "Hello world"title(): Converts the first letter of each word to uppercase."hello world".title() # Output: "Hello World"swapcase(): Swaps the case of all characters in the string (uppercase becomes lowercase and vice versa)."Hello World".swapcase() # Output: "hELLO wORLD"
2. Searching and Checking Methods
find(substring): Returns the lowest index where the substring is found in the string, or-1if not found."hello world".find("world") # Output: 6rfind(substring): Returns the highest index where the substring is found, or-1if not found."hello world".rfind("l") # Output: 9index(substring): Likefind(), but raises aValueErrorif the substring is not found."hello world".index("world") # Output: 6rindex(substring): Likerfind(), but raises aValueErrorif the substring is not found."hello world".rindex("l") # Output: 9startswith(prefix): ReturnsTrueif the string starts with the specified prefix."hello world".startswith("hello") # Output: Trueendswith(suffix): ReturnsTrueif the string ends with the specified suffix."hello world".endswith("world") # Output: Truecount(substring): Returns the number of occurrences of the substring in the string."hello world".count("l") # Output: 3isalnum(): ReturnsTrueif all characters in the string are alphanumeric (letters or digits) and there is at least one character."hello123".isalnum() # Output: Trueisalpha(): ReturnsTrueif all characters in the string are alphabetic and there is at least one character."hello".isalpha() # Output: Trueisdigit(): ReturnsTrueif all characters in the string are digits."12345".isdigit() # Output: Trueisspace(): ReturnsTrueif all characters in the string are whitespace characters." ".isspace() # Output: Trueisupper(): ReturnsTrueif all characters in the string are uppercase and there is at least one alphabetic character."HELLO".isupper() # Output: Trueislower(): ReturnsTrueif all characters in the string are lowercase and there is at least one alphabetic character."hello".islower() # Output: True
3. Modifying and Manipulating Strings
replace(old, new): Replaces all occurrences of the substringoldwithnew."hello world".replace("world", "Python") # Output: "hello Python"strip(): Removes leading and trailing whitespace (or specified characters) from the string." hello ".strip() # Output: "hello"lstrip(): Removes leading whitespace (or specified characters) from the string." hello".lstrip() # Output: "hello"rstrip(): Removes trailing whitespace (or specified characters) from the string."hello ".rstrip() # Output: "hello"join(iterable): Joins the elements of an iterable (like a list) into a single string, using the string as a separator.", ".join(["apple", "banana", "cherry"]) # Output: "apple, banana, cherry"split(separator): Splits the string into a list of substrings using the specified separator."hello world".split() # Output: ["hello", "world"]rsplit(separator): Splits the string from the right side."apple,banana,cherry".rsplit(",", 1) # Output: ['apple,banana', 'cherry']partition(separator): Splits the string into a tuple of three parts: the part before the separator, the separator itself, and the part after it."hello world".partition(" ") # Output: ("hello", " ", "world")rpartition(separator): Likepartition(), but splits from the right."hello world".rpartition(" ") # Output: ("hello", " ", "world")splitlines(): Splits the string at line breaks and returns a list of lines."hello\nworld".splitlines() # Output: ["hello", "world"]
4. String Formatting Methods
format(*args, **kwargs): Formats the string by inserting values into placeholders{}."Hello, {}!".format("Alice") # Output: "Hello, Alice!"format_map(mapping): Similar toformat(), but uses a dictionary for formatting."Hello, {name}!".format_map({"name": "Alice"}) # Output: "Hello, Alice!"zfill(width): Pads the string on the left with zeros until the total string length equals the specified width."42".zfill(5) # Output: "00042"
5. Character-Related Methods
ord(c): Returns the Unicode code point of the given character.ord('a') # Output: 97chr(i): Returns the string representing a character whose Unicode code point is the integeri.chr(97) # Output: 'a'
6. Aligning and Justifying Strings
center(width): Centers the string within the specified width, padding with spaces."hello".center(10) # Output: " hello "ljust(width): Left-aligns the string within the specified width, padding with spaces."hello".ljust(10) # Output: "hello "rjust(width): Right-aligns the string within the specified width, padding with spaces."hello".rjust(10) # Output: " hello"
Summary:
- Python provides various string methods for searching, manipulating, formatting, and checking strings.
- Modifying methods like
replace(),strip(),join(), andsplit()are commonly used for transforming strings. - Checking methods like
isalnum(),isalpha(),isdigit(), andstartswith()are useful for validating strings. - Formatting methods like
format()andzfill()allow for dynamic string creation.