Python offers a wide range of built-in string methods in order for us to manipulate and process strings efficiently. String in Python, is an immutable data type, therefore, all of these methods return a new string, keeping the original string unchanged.
Python 'str' class offers various methods to change the case of the characters in a string. The following table shows the different methods:
| S. No. | String Method | Description |
|---|---|---|
| 1 | str.upper() | This method converts all characters in the string to uppercase. |
| 2 | str.lower() | This method converts all characters in the string to lowercase. |
| 3 | str.title() | This method capitalizes the first letter of each word. |
| 4 | str.capitalize() | This method capitalizes only the first letter of the string. |
| 5 | str.swapcase() | This method swaps the uppercase letters in the string to the lowercase; and vice versa. |
Let us see an example showing the implementation of these string methods in Python.
Output:
I LOVE LEARNING PYTHON python is fun with tpoint tech Welcome To Tpoint Tech Welcome to tpoint tech lEARNING pYTHON fEELS wONDERFUL
Explanation:
In the above example, we have used different string methods like upper(), lower(), title(), capitalize(), and swapcase(), to change the case of the specified strings in Python.
The 'str' class of Python also offers various methods to locate substrings in strings. The following table shows the different methods:
| S. No. | String Method | Description |
|---|---|---|
| 1 | str.find(substring) | This method is used to return the index of the first occurrence of substring, or -1 if not found. |
| 2 | str.index(substring) | This method is similar to the find() method; however it raises an error if substring is not found. |
| 3 | str.rfind(substring) | This method is used to return the highest index of substring, or -1 if not found. |
| 4 | str.rindex(substring) | This method is similar to the rfind() method; however it raises an error if substring is not found. |
| 5 | str.count(substring) | This method counts the number of occurrences of substring. |
| 6 | str.startswith(prefix) | This method is used for checking if the string starts with prefix. |
| 7 | str.endswith(suffix) | This method is used to check if the string ends with suffix. |
Let us see an example showing the implementation of these string methods in Python.
Output:
Index of 'Tpoint': 29 Last index of 'Tpoint': 42 Index of 'students': 86 Last index of 'learning': 273 Starts with 'Tpoint': False Ends with 'basics.': False Count of 'Tpoint': 2
Explanation:
In the above example, we have used different string methods like find(), rfind(), index(), rindex(), count(), startswith(), and endswith() to relocate the substrings in the given string.
The 'str' class of Python also offers different methods that help us break and combine strings. The list of such methods is shown in the following table:
| S. No. | String Method | Description |
|---|---|---|
| 1 | str.split(sep) | This method is used to split the string by sep into a list |
| 2 | str.rsplit(sep, maxsplit) | This method is used to split from the right side |
| 3 | str.partition(sep) | This method is used to split into three parts: before, sep, and after |
| 4 | str.join(iterable) | This method is used to join elements of an iterable with str as a separator |
Let us see an example showing the implementation of these string methods in Python.
Output:
Split string: ['Learning', 'Python', 'is', 'fun', 'with', 'Tpoint', 'Tech.']
Right split string: ['Learning Python is fun with', 'Tpoint', 'Tech.']
Partitioned string: ('Learning Python is fun with Tpoint Tech.', '', '')
Joined string: Tpoint Tech offers best tutorials to learn Python
Joined string with comma: Tpoint, Tech, offers, best, tutorials, to, learn, Python
Explanation:
In the above example, we have used different string methods like split(), rsplit(), partition(), and join() to split and join the given string.
The 'str' class of Python also offers different methods that help us check whether a string contains only specific types of characters. The list of such methods is shown in the following table:
| S. No. | String Method | Description |
|---|---|---|
| 1 | str.isalpha() | This method is used to return True if all characters are alphabetic |
| 2 | str.isdigit() | This method is used to return True if all characters are digits |
| 3 | str.isalnum() | This method is used to return True if all characters are alphanumeric |
| 4 | str.isspace() | This method is used to return True if all characters are spaces |
| 5 | str.islower() | This method is used to return True if all characters are lowercase |
| 6 | str.isupper() | This method is used to return True if all characters are uppercase |
| 7 | str.istitle() | This method is used to return True if the string is in title case |
Let us see an example showing the implementation of these string methods in Python.
Output:
Given String: Welcome Is alphabetic (str.isalpha()): True Is digit (str.isdigit()): False Is alphanumeric (str.isalnum()): True Is space (str.isspace()): False Is lowercase (str.islower()): False Is uppercase (str.isupper()): False Is titlecase (str.istitle()): True ------------------------------ Given String: PYTHON Is alphabetic (str.isalpha()): True Is digit (str.isdigit()): False Is alphanumeric (str.isalnum()): True Is space (str.isspace()): False Is lowercase (str.islower()): False Is uppercase (str.isupper()): True Is titlecase (str.istitle()): False ------------------------------ Given String: Tpoint Tech Is alphabetic (str.isalpha()): False Is digit (str.isdigit()): False Is alphanumeric (str.isalnum()): False Is space (str.isspace()): False Is lowercase (str.islower()): False Is uppercase (str.isupper()): False Is titlecase (str.istitle()): True ------------------------------ Given String: Is alphabetic (str.isalpha()): False Is digit (str.isdigit()): False Is alphanumeric (str.isalnum()): False Is space (str.isspace()): True Is lowercase (str.islower()): False Is uppercase (str.isupper()): False Is titlecase (str.istitle()): False ------------------------------ Given String: hello friends Is alphabetic (str.isalpha()): False Is digit (str.isdigit()): False Is alphanumeric (str.isalnum()): False Is space (str.isspace()): False Is lowercase (str.islower()): True Is uppercase (str.isupper()): False Is titlecase (str.istitle()): False ------------------------------
Explanation:
In the above example, we have defined a function to validate a given string. Inside this function, we have used different string methods like isalpha(), isdigit(), isalnum(), isspace(), islower(), isupper() and istitle() to validate the string. We have tested the outputs of these methods on different examples.
The 'str' class of Python also offers different methods to format strings for display. The following table shows the number of string methods available for string formatting:
| S. No. | String Method | Description |
|---|---|---|
| 1 | str.center(width, fillchar) | This method is used to center the string with padding. |
| 2 | str.ljust(width, fillchar) | This method is used to align the string to the left with padding. |
| 3 | str.rjust(width, fillchar) | This method is used to align the string to the right with padding. |
| 4 | str.zfill(width) | This method is used to pad the string with zeros. |
| 5 | str.format() | This method is used to format a string dynamically. |
| 6 | f"{var}" | This method is used to provide f-string formatting. |
Let us see an example showing the implementation of these string methods in Python.
Output:
Tpoint----
----Tpoint
--Tpoint--
My name is Morgan and I am 29 years old.
My name is Morgan and I am 29 years old.
01243
3.14
00003.14
Tpoint
Tpoint
Tpoint
Explanation:
In the above example, we have used different string methods like ljust(), rjust(), center(), zfill(), format(), and f-string on the string to align and format them.
The 'str' class of Python also offers different methods to convert strings into different encodings. The following table shows the number of string methods available for string encoding and decoding:
| S. No. | String Method | Description |
|---|---|---|
| 1 | str.encode(encoding) | Converts string to bytes using encoding |
| 2 | bytes.decode(encoding) | Converts bytes back to string |
Let us see an example showing the implementation of these string methods in Python.
Output:
Encoded text: b'This is a sample text string with special characters like \xc3\xa9\xc3\xa0\xc3\xa7\xc3\xbc\xc3\xb6.' Decoded text: This is a sample text string with special characters like éàçüö. The string contains characters that cannot be encoded using ASCII. Base64 encoded text: b'VGhpcyBpcyBhIHNhbXBsZSB0ZXh0IHN0cmluZyB3aXRoIHNwZWNpYWwgY2hhcmFjdGVycyBsaWtlIMOpw6DDp8O8w7Yu' Base64 decoded text: This is a sample text string with special characters like éàçüö.
Explanation:
In the above example, we have shown the use of encode() and decode() methods to encode the given text string to different encodings (like UTF-8, ASCII, and Base64) and decode them.
The following is the complete list of String Methods available in Python for programmers to play with Strings.
| S. No. | String Method | Description |
|---|---|---|
| 1 | capitalize() | This method converts the first character to uppercase. |
| 2 | casefold() | This method converts the string to lowercase (more aggressive than lower()). |
| 3 | center(width, fillchar) | This method centers the string with the given width and optional fill character. |
| 4 | count(substring, start, end) | This method counts occurrences of a substring in the string. |
| 5 | encode(encoding, errors) | This method returns an encoded version of the string. |
| 6 | endswith(suffix, start, end) | This method checks if the string ends with the given suffix. |
| 7 | expandtabs(tabsize) | This method replaces tab characters (\t) with spaces. |
| 8 | find(substring, start, end) | This method returns the index of the first occurrence of the substring (or -1 if not found). |
| 9 | format(*args, **kwargs) | This method formats the string with given arguments. |
| 10 | format_map(mapping) | This method formats the string using a dictionary mapping. |
| 11 | index(substring, start, end) | This method is like find(), but raises a ValueError if the substring is not found. |
| 12 | isalnum() | This method checks if all characters are alphanumeric. |
| 13 | isalpha() | This method checks if all characters are alphabetic. |
| 14 | isascii() | This method checks if all characters are ASCII. |
| 15 | isdecimal() | This method checks if all characters are decimals. |
| 16 | isdigit() | This method checks if all characters are digits. |
| 17 | isidentifier() | This method checks if the string is a valid Python identifier. |
| 18 | islower() | This method checks if all characters are lowercase. |
| 19 | isnumeric() | This method checks if all characters are numeric. |
| 20 | isprintable() | This method checks if all characters are printable. |
| 21 | isspace() | This method checks if the string contains only whitespace. |
| 22 | istitle() | This method checks if the string follows the title case. |
| 23 | isupper() | This method checks if all characters are uppercase. |
| 24 | join(iterable) | This method joins elements of an iterable with the string as a separator. |
| 25 | ljust(width, fillchar) | This method left-justifies the string within a given width. |
| 26 | lower() | This method converts all characters to lowercase. |
| 27 | lstrip(chars) | This method removes leading whitespace or specified characters. |
| 28 | maketrans(x, y, z) | This method creates a translation table for translate(). |
| 29 | partition(separator) | This method splits the string into a tuple (before separator, separator, after separator). |
| 30 | removeprefix(prefix) | This method removes the specified prefix from the string. |
| 31 | removesuffix(suffix) | This method removes the specified suffix from the string. |
| 32 | replace(old, new, count) | This method replaces the occurrences of old with new. |
| 33 | rfind(substring, start, end) | This method finds the last occurrence of a substring. |
| 34 | rindex(substring, start, end) | This method is like rfind(), but raises a ValueError if not found. |
| 35 | rjust(width, fillchar) | This method right-justifies the string within a given width. |
| 36 | rpartition(separator) | This method splits the string into a tuple from the right. |
| 37 | rsplit(separator, maxsplit) | This method splits the string from the right. |
| 38 | rstrip(chars) | This method removes trailing whitespace or specified characters. |
| 39 | split(separator, maxsplit) | This method splits the string into a list. |
| 40 | splitlines(keepends) | This method splits the string at line breaks. |
| 41 | startswith(prefix, start, end) | This method checks if the string starts with the given prefix. |
| 42 | strip(chars) | This method removes both leading and trailing whitespace or specified characters. |
| 43 | swapcase() | This method swaps uppercase characters to lowercase and vice versa. |
| 44 | title() | This method converts the first character of each word to uppercase. |
| 45 | translate(table) | This method translates the string using a given translation table. |
| 46 | upper() | This method converts all characters to uppercase. |
| 47 | zfill(width) | This method pads the string with zeros on the left. |
In this tutorial, we have learned about the various String Methods available in Python to manipulate Strings.
We request you to subscribe our newsletter for upcoming updates.