Python String Methods
Learn Python String methods to get better at writing efficient and elegant code.
Image by Author
In this blog, we will be reviewing Python’s built-in methods to operate on Strings. You can use these methods to perform boolean checks and replace or change the form of the string.
Code Samples
upper
The `upper()` method changes all lowercase alphabets into uppercase.
text = 'knoWledge dIsCoverY NuggETS'
# Converting string to uppercase
new_string = text.upper()
print(f"Before: {text}\nAfter: {new_string}\n")
Before: knoWledge dIsCoverY NuggETS
After: KNOWLEDGE DISCOVERY NUGGETS
replace
The `replace()` method requires two arguments to replace all occurrences of a substring with another substring.
# Replacing the string
new_string = text.replace("knoWledge dIsCoverY ","KD")
print(f"Before: {text}\nAfter: {new_string}\n")
Before: knoWledge dIsCoverY NuggETS
After: KDNuggETS
find
The `find()` will search for a substring and if it is found, it will return the lowest index of the substring.
# Find the string
new_string = text.find("dIsCoverY")
print(f"The string is at {new_string} index\n")
The string is at 10 index
isnumeric
The `isnumeric()` method returns “True” if all of the characters in the string are numeric.
# Is the text numerical?
new_string = text.isnumeric()
print(f"Is the text numerical? {new_string}\n")
print(f"Is·the·text·numerical?·{new_string}\n")
#·Is·the·text·numerical?
new_string·=·text.isnumeric()
Is the text numerical? False
List of all Python String Methods
Case Change
- lower(): it changes all uppercase characters to lowercase.
- capitalize(): it changes the first character of the string to uppercase.
- upper(): it changes all lowercase characters to uppercase.
- title(): it changes string to title case.
- casefold(): it implements caseless string matching.
- swapcase(): it changes all uppercase characters to lowercase and lowercase to uppercase.
Checks
- startswith(): it returns “True” if the string starts with the given substring.
- endswith(): it returns “True” if the string ends with the given substring.
- isalnum(): it checks if all characters in the string are alphanumeric or not.
- isalpha(): it checks if all characters in the string are alphabets or not.
- isdecimal(): it checks if all characters in the string are decimal or not.
- isdigit(): it checks if all characters in the string are digits or not.
- isidentifier(): it checks if the string is a valid identifier or not.
- islower(): it checks if all characters in the string are lowercase or not.
- isnumeric(): it checks if all characters in the string are numeric or not.
- isprintable(): it returns “True” if all characters in the string are printable or the string is empty
- isspace(): it checks if all characters in the string are whitespace characters or not.
- istitle(): it checks if all characters in the string are title case or not.
- isupper(): it checks if all characters in the string are uppercase or not.
Split and Join
- join(): it returns a concatenated string.
- partition(): it splits the string on the first occurrence of the separator.
- rpartition(): it splits the string into three parts.
- rsplit(): it splits the string from the right using a specified separator.
- splitlines(): it splits the lines at line boundaries.
- split(): it splits the string using a specified separator.
Padding and Cleaning
- center(): Pad the string with the specified character.
- ljust(): It left aligned the string using the specified width.
- rjust(): It right aligned the string using the specified width.
- lstrip(): it removes the leading characters from the string.
- rstrip(): it removes the trailing characters from the string.
- strip(): it removes both leading and trailing characters from the string.
- zfill(): it returns a copy of the string with ‘0’ characters padded to the left side of the string.
Find and Replace
- encode(): it encodes the string using a specified encoding scheme.
- find(): it returns the lowest index of the specified substring.
- rfind(): it returns the heights index of the specified substring.
- index(): it returns the position of the first occurrence of a substring in a string.
- rindex(): it returns the highest index of the substring inside the string.
- replace(): it requires two arguments to replace all occurrences of a substring with another substring.
Miscellaneous
- count(): it counts the number of occurrences of a substring in the string.
- expandtabs(): it specifies the amount of space to be substituted with the “\t” symbol in the string.
- maketrans(): it returns a translation table.
- translate(): it changes the string using translation mappings.
- format(): it formats the string for console printing.
- format_map(): it formats specified values in a string using a dictionary.
Learning Resources
Abid Ali Awan (@1abidaliawan) is a certified data scientist professional who loves building machine learning models. Currently, he is focusing on content creation and writing technical blogs on machine learning and data science technologies. Abid holds a Master's degree in Technology Management and a bachelor's degree in Telecommunication Engineering. His vision is to build an AI product using a graph neural network for students struggling with mental illness.