String Methods
String methods in Python are built-in functions that allow you to manipulate and analyze text data. These methods help you perform common operations such as searching, modifying, and formatting strings efficiently.
Commonly Used String Methods
-
str.upper()andstr.lower():- Convert a string to uppercase or lowercase.
- Example:
text = "Hello, World!" upper_text = text.upper() # "HELLO, WORLD!" lower_text = text.lower() # "hello, world!"
-
str.capitalize()andstr.title():- Capitalize the first letter of a string or capitalize the first letter of each word.
- Example:
text = "hello, world!" capitalized_text = text.capitalize() # "Hello, world!" title_text = text.title() # "Hello, World!"
-
str.strip(),str.lstrip(), andstr.rstrip():- Remove leading and/or trailing whitespace (or other specified characters).
- Example:
text = " Hello, World! " stripped_text = text.strip() # "Hello, World!" left_stripped = text.lstrip() # "Hello, World! " right_stripped = text.rstrip() # " Hello, World!"
-
str.replace():- Replace occurrences of a substring with another substring.
- Example:
text = "Hello, World!" replaced_text = text.replace("World", "Python") # "Hello, Python!"
-
str.split()andstr.join():split(): Split a string into a list of substrings based on a delimiter.join(): Join a list of strings into a single string with a specified delimiter.- Example:
text = "Hello, World!" words = text.split(", ") # ["Hello", "World!"] joined_text = " - ".join(words) # "Hello - World!"
-
str.find()andstr.index():find(): Return the lowest index of the substring if found, otherwise return-1.index(): Similar tofind(), but raises aValueErrorif the substring is not found.- Example:
text = "Hello, World!" index = text.find("World") # 7 # index_not_found = text.index("Python") # Raises ValueError
-
str.startswith()andstr.endswith():- Check if a string starts or ends with a specified substring.
- Example:
text = "Hello, World!" starts_with = text.startswith("Hello") # True ends_with = text.endswith("World!") # True
-
str.count():- Count the number of occurrences of a substring in a string.
- Example:
text = "Hello, World! Hello again!" count = text.count("Hello") # 2
-
str.isalpha(),str.isdigit(), andstr.isalnum():isalpha(): Check if the string consists only of alphabetic characters.isdigit(): Check if the string consists only of digits.isalnum(): Check if the string consists only of alphanumeric characters (letters and numbers).- Example:
text_alpha = "Hello" text_digit = "12345" text_alnum = "Hello123" is_alpha = text_alpha.isalpha() # True is_digit = text_digit.isdigit() # True is_alnum = text_alnum.isalnum() # True
-
str.center(),str.ljust(), andstr.rjust():- Adjust the alignment of a string to be centered, left-justified, or right-justified within a given width.
- Example:
text = "Hello" centered = text.center(10, "-") # "--Hello---" left_justified = text.ljust(10, "-") # "Hello-----" right_justified = text.rjust(10, "-") # "-----Hello"
Advanced String Methods
-
str.zfill():- Pad a string on the left with zeros until it reaches the specified length.
- Example:
text = "42" padded_text = text.zfill(5) # "00042"
-
str.partition()andstr.rpartition():- Split the string into a tuple with three parts: the part before the separator, the separator itself, and the part after the separator.
- Example:
text = "Hello, World!" parts = text.partition(", ") # ("Hello", ", ", "World!")
-
str.casefold():- Return a case-insensitive version of the string, useful for caseless matching.
- Example:
text = "Hello, World!" casefolded_text = text.casefold() # "hello, world!"