String Methods
General Methods
Case Conversion
· capitalize(): Converts the first character to uppercase and the rest to lowercase.
Python
text =
"hello, world!"
capitalized_text = text.capitalize()
# Output: "Hello, world!"
· lower(): Converts all characters to lowercase.
Python
text =
"HELLO, WORLD!"
lower_text = text.lower()
# Output: "hello, world!"
· upper(): Converts all characters to uppercase.
Python
text =
"hello, world!"
upper_text = text.upper()
# Output: "HELLO, WORLD!"
· swapcase(): Swaps cases, lower to upper and vice versa.
Python
text =
"HeLlO, WoRlD!"
swapped_text = text.swapcase()
# Output: "hEllO, wOrLd!"
· title(): Converts the first character of each word to uppercase.
Python
text =
"hello world"
title_case_text = text.title()
# Output: "Hello World"
· casefold(): Converts string to lowercase for caseless comparisons.
Python
text =
"HELLO, WORLD!"
casefolded_text = text.casefold()
# Output: "hello, world!"
Checking String Content
· isalnum(): Returns True if all characters are alphanumeric.
· isalpha(): Returns True if all characters are alphabetic.
· isdigit(): Returns True if all characters are digits.
· isspace(): Returns True if all characters are whitespace.
· islower(): Returns True if all characters are lowercase.
· isupper(): Returns True if all characters are uppercase.
· istitle(): Returns True if the string is in title case.
Searching Within a String
· find(): Returns the index of the first occurrence of a substring.
· rfind(): Returns the index of the last occurrence of a substring.
· index(): Similar to find(), but raises a ValueError if not found.
· rindex(): Similar to rfind(), but raises a ValueError if not found.
· startswith(): Returns True if the string starts with the specified value.
· endswith(): Returns True if the string ends with the specified value.
Modifying Strings
· strip(): Removes leading and trailing whitespace.
· lstrip(): Removes leading whitespace.
· rstrip(): Removes trailing whitespace.
· replace(): Replaces occurrences of a substring with another.
· join(): Joins elements of an iterable into a string.
· split(): Splits a string into a list of substrings based on a separator.
· partition(): Splits a string into three parts based on a separator.
· rpartition(): Splits a string into three parts, starting from the right.
Other Methods
· count(): Returns the number of occurrences of a substring.
· expandtabs(): Replaces tabs with spaces.
· center(): Centers a string within a specified width.
· ljust(): Left-justifies a string within a specified width.
· rjust(): Right-justifies a string within a specified width.
· zfill(): Pads a string with zeros to a specified length.
· encode(): Encodes a string into a bytes object.
· decode(): Decodes a bytes object into a string.
·
maketrans(): Creates a translation
table for use with the translate()
method.
· translate(): Translates characters using a translation table.