Python String Methods Flashcards
Removes leading and trailing whitespace (or specified characters).
strip()
" hello ".strip() # Output: "hello"
Replaces a specified substring with another substring.
replace()
"hello world".replace("world", "Python") # Output: "hello Python"
Splits a string into a list based on a delimiter.
split()
"a,b,c".split(",") # Output: ["a", "b", "c"]
Joins elements of an iterable into a string using a specified separator.
join()
", ".join(["a", "b", "c"]) # Output: "a, b, c"
Converts all characters in a string to lowercase.
lower()
"HELLO".lower() # Output: "hello"
Converts all characters in a string to uppercase.
upper()
"hello".upper() # Output: "HELLO"
Checks if a string starts with a specified substring.
startswith()
"hello".startswith("he") # Output: True
Checks if a string ends with a specified substring.
endswith()
"hello".endswith("lo") # Output: True
Checks if all characters in a string are digits.
isdigit()
"123".isdigit() # Output: True
Checks if all characters are alphanumeric (letters or numbers).
isalnum()
"abc123".isalnum() # Output: True
Checks if all characters in a string are whitespace.
isspace()
" ".isspace() # Output: True
Formats a string using placeholders.
format()
"Hello, {}".format("Alice") # Output: "Hello, Alice"
Pads the string with zeros to make it a specified length.
zfill()
"5".zfill(3) # Output: "005"
Returns the first index of a specified substring or -1 if not found.
find()
"hello".find("e") # Output: 1
Returns the number of occurrences of a specified substring.
count()
"hello hello".count("hello") # Output: 2