String Methods Python
Video Tutorial
Python String Methods
1. capitalize()
Returns a copy of the original string, with only the first letter as upper case and keeping all the other characters as lower case.
Syntax:
Application:
Output:
Check out this article to learn more about Capitalize in Python.
2. casefold()
Returns a string with each character as lower case.
Syntax:
Application:
Output:
3. center()
Returns a string of specified length with specific leading and trailing padded characters.
Syntax:
str.center(width, fillChar)
- width is the length of the resulting string.
- fillChar (optional) is the character to be padded. If not provided takes space as default parameter.
Returns a string with padded characters and of the mentioned length.
Application:
Output:
Check out this article to know more about Centre() in Python
4. count()
Returns the total number of occurrences of a substring in a string.
Syntax:
str.count(substring, start, end)
- Substring is the substring you’re counting for.
- Start (optional): index where search starts. By default ‘0’.
- Stop (optional) index where search stops. By default it stops at the last index.
Note that the searching stops right before the ‘stop’ index
Application:
Output:
Check out this article to know more about Count() in Python.
5. encode()
Returns an encoded version of the given string.
Syntax:
- encoding (Optional)- specific encoding type a requested string has to be encoded to
- errors (Optional)- types of responses that are to be returned if encoding fails:
- strict (default response) raises a UnicodeDecodeError exception.
- ignore – if unencodable unicodes are to be ignored.
- replace – if unencodable unicodes are to be replaced with ‘?’
- xmlcharrefreplace replaces xml character reference instead of unencodable unicode.
- backslashreplace – replaces \uNNNN escape sequence with unencodable unicode.
- namereplace – replaces a \N{…} escape sequence instead of unencodable unicode.
Application:
Output:
Click here, To know more about Encode() in python.
6. endsWith()
Returns true if a string ends with a specified suffix.
Syntax:
- Suffix: string or tuple of strings as suffixes to be verified.
- Start (Optional): beginning position where suffix is to be checked.
- Stop (Optional): stopping position until where suffix is to be checked.
Application:
Output:
Check out this article to know more about Endswith() in python.
7. expandTabs()
Returns a string by replacing all the ‘\t’ characters with white space characters.
Syntax:
Parameters:
- Tabsize(optional): integer value that determines the number of white space characters before the next character. If not provided, the default value is 8.
Application:
Output:
8. find()
Returns index of first occurrence of a substring in a string, if found. If not found returns -1.
Syntax:
Parameters:
- substr: substring that is to be searched for
- Start & end: both are the optional parameters. They define the range of index of the string between which substring has to be found.
Application:
Output:
Check out this article to know more about Find Function in Python.
9. format()
Returns a string by replacing placeholders in the original string with the values provided in the parameters. (Provided, placeholders are a part of the requested string. )
Syntax:
(parameters depend on number of placeholders exposed in the string)
Parameters:
There are two types of parameters:
- Positional Parameter: in this case, the placeholders in the string are indices, and value for each index is passed to the format’s parameters that replace these placeholders with these values. Such parameters that replace on the basis of index or position of placeholder are called positional parameters.
- Keyword Parameter: These parameters are of type key-value pair i.e. the placeholders are keys here and the parameters are of key-value format, this allows values corresponding to the keys to be replaced with placeholder keys.
Application:
Output:
10. formatMap()
Is similar to the format method, Returns a string by replacing the placeholders in the original string with the values provided as key-value objects (dictionary ) in parameters.
Application:
Output:
greetings John, your balance is 1000
11. index()
Returns index of first occurrence of a substring in a string, if found. (Just like find())
Syntax:
Parameters:
- substr: substring that is to be searched for.
- Start & end: both are the optional parameters. They define the range of index of the string between which substring has to be found.
Returns index of the first occurrence of the substring if found. If not, throw an exception.
Difference between find() and index() is that find() returns ‘-1’ where index throws an exception.
Application:
Output:
12. isalnum()
Returns true if all characters in a string are alphanumeric (i.e both alphabets or numeric), else returns false.
Syntax:
Does not take any parameters
Application:
Output:
Click here, to know more about isalnum() in Python.
13. isalpha()
Returns true if all characters in the string are alphabets, else returns false.
Syntax:
Does not take any parameters
Application:
Output:
Click here, To know more about isalpha() in python.
14. isdecimal()
Returns true if all characters in the string are decimal, else returns false.
Syntax:
Does not take any parameters
NOTE: Subscripts and superscripts are considered as digits and not decimal, hence this method returns false for them. Similarly fractions, currency numerators and fractions are considered numeric but not decimal, hence returns false for it as well.
Application:
Output:
15. isdigit
Returns true if all characters in the string are digits, else returns false.
Syntax:
Does not take any parameters
Subscripts and Superscripts are considered as digits, hence this method returns true for them.
Similarly fractions, currency numerators and fractions are considered numeric but not digit, hence returns false for it as well.
Application:
Output:
Click here, To know more about isdigit() in Python.
16. isidentifier()
Returns true if the string is a valid identifier in python, else returns false.
Syntax:
Application:
Output:
17. islower()
Returns true if all alphabets in the string are lowercase, else returns false.
Syntax:
Does not matter if the string contains special characters or numbers, if it contains characters and are lower returns true.
Application:
Output:
18. isnumeric()
method supports Digits, Vulgar Fractions, Subscripts, Superscripts, Roman Numerals, Currency Numerators.
Click here, To know more about isnumeric() in python.
19. isprintable()
Returns true if all characters in the string are printable. If even a single character is non printable, it returns false.
Printable Characters:
- letters and symbols
- digits
- punctuation
- Whitespace
Syntax:
Application:
Output:
20. isspace()
Returns true if there are only white space characters in the string. If not, returns false.
Syntax:
Application:
Output:
21. istitle()
Returns true if string is a titled cased string
Syntax:
Does not take any parameter.
Application:
Output:
22. isupper()
Returns true if all characters in a string are uppercase, else returns false.
Syntax:
Does not take any parameter.
Application:
Output:
23. join()
Returns a string by joining all the elements of an iterable collection.
These iterable collections include: List, Tuple, Set & Dictionary.
Syntax:
Parameters:
Collection: These iterable collections include: List, Tuple, Set & Dictionary.
Note:
Join(), joins keys of the dictionary and NOT the values. When joining sets, the resulting string may be any random join of elements of the set, as set is an unordered collection. Application:
Output:
Click here, To know more about Join() in Python.
24. ljust()
Returns a left justified string of a given width.
Syntax:
Parameters:
Width: width of the string to be returned. If width is less then or equal to the original string, then returns the original string. Fillchar: an optional parameter and is the character to fill the remaining space of the width at left side of the string. If this parameter is not provided then the string returned has filled char as space ‘ ’. Application:
Output:
Read this article to know more about ljust() in Python.
25. lower()
Returns by converting all lowercase characters to uppercase characters.
Syntax:
Does not take any parameter.
Doesn’t matter if the string contains numbers or special characters, it just looks for lowercase characters and converts them to upper case characters. If lowercase characters do not exist, returns the original string.
Application:
Output:
26. lstrip()
Returns a string with leading characters removed. Leading characters that are removed depend on the argument passed to the parameter.
Syntax:
Parameter:
charToBeStripped:(optional) set of characters to be removed from the leading end. If not provided, this method considers ‘ ’ (space) as the default argument. Application:
Output:
27. maketrans()
Returns a mapping table object that can be used with the translate() method to replace specific characters.
Syntax:
Parameters:
- X: if only one parameter is provided, it should be a dictionary with 1:1 mapping. As this 1:1 mapping will map character to its translation.
- Y:(Optional) if this parameter is provided, make sure ‘x’ and ‘y’ both are strings of equal length. Each character in the X string is a replacement to its corresponding index in the Y string.
- Z: If three arguments are passed, each character in the third argument is mapped to None.
Application:
Output:
Click here to know more about maketrans() in Python.
28. partition()
Returns a 3 element tuple, by splitting the string at the first occurrence of the argument and returns a tuple containing the string before the argument, the argument and string after the argument.
Syntax:
Parameters:
Separator: will part the string considering only the first occurance of this ‘Separator’.
Note: if separator is not found, the method returns a tuple containing the string itself, followed by two empty strings.
Application:
Output:
29. replace()
Returns a string where all occurrences of a substring are replaced with another substring.
Syntax:
Parameters:
- Substr1
to be replaced. - Substr2: substring to be replaced with.
- Count: (Optional) no of occurrences of substr1 you want to replace with substr2. If not provided, this method replaces all the occurrences of substr1 with substr2.
Application:
Output:
Check out this article to know more about replace() method in python .
30. rfind()
Returns the index of the latest occurrence of substring to be searched for. If not found returns -1.
Syntax:
Parameters:
- Substr
that is to be searched for. - Start:(Optional) start index of the range in which substring is to be searched.
- End:(Optional) end index of the range in which substring is to be searched for. If the start index is not provided, it automatically searches from start until the end of the string.
If the end index is not provided, it automatically takes searches from start until the end of the string.
Application:
Check out this article to learn more about rfind() in Python.
31. rindex()
Returns the index of the latest occurrence of substring to be searched for. If not found, throws an exception. This method is the same as rfind, only difference is rfind returns -1 incase substring is not found.
Syntax:
Parameters:
- Substr
that is to be searched for. - Start:(Optional) start index of the range in which substring is to be searched.
- End:(Optional) end index of the range in which substring is to be searched for. If the start index is not provided, it automatically searches from start until the end of the string
If the end index is not provided, it automatically takes searches from start until the end of the string.
Application:
Output:
32. rjust()
Returns a right justified string of given width.
Syntax:
Parameters:
- Width: width of the string to be returned. If width is less then or equal to the original string, then returns the original string.
- Fillchar: an optional parameter and is the character to fill the remaining space of the width at right side of the string. If this parameter is not provided then the string returned has filled char as space ‘ ’.
Application:
Output:
Click here to know more about partition() in Python.
33. rpartition()
Returns a 3 element tuple, by splitting the string at the last occurrence of the argument and returns a tuple containing the string before the last occurrence of argument, the argument and string after the last occurrence of argument.
Syntax:
Parameters:
Separator: will part the string considering only the first occurance of this ‘Separator’.
Note: if separator is not found, the method returns a tuple containing the string itself, followed by two empty strings.
Output:
34. rsplit()
Returns a list of strings by splitting the original string into substrings on the basis of a separator. By default the separator is a space ‘ ’.
Syntax:
Parameters:
- Separator(Optional): Split method splits the string on the basis of this separator, starting from the right. And then returns a list of substrings that were fetched by splitting the original string. By default the separator is space’ ’.
- MaxSplit(Optional): it determines how many times you want to split the string. For example let’s say your separator is ‘|’ and there are 10 occurrences of ‘|’ in your string. By default the string will be splitted wherever it finds ‘|’ from the right. But if you give value to this parameter let’s say 5. The string will split for first 5 occurrences of ‘| from the right.
This method is similar to split(). Only difference is that split performs the action from the left i.e. looks for the occurrence of the separator from the left unlike rsplit that looks from the right.
Application:
Output:
35. rstrip()
Returns a string by removing the trailing characters from the right. (depends on the parameter provided)
Syntax:
Parameters:
charactersToBeRemoved(Optional): determines the set of characters to be considered while removing trailing characters. If not provided space is considered as the only character to be removed.
Application:
Output:
36. split()
Returns a list of strings by splitting the original string into substrings on the basis of a separator. By default the separator is a space ‘ ’.
Syntax:
Parameters:
- Separator(Optional): Split method splits the string on the basis of this separator, starting from the right. And then returns a list of substrings that were fetched by splitting the original string. By default the separator is space’ ’.
- MaxSplit(Optional): it determines how many times you want to split the string. For example let’s say your separator is ‘|’ and there are 10 occurrences of ‘|’ in your string. By default the string will be splitted wherever it finds ‘|’ from the left. But if you give value to this parameter let’s say 5. The string will split for first 5 occurrences of ‘| from the left.
This method is similar to rsplit(). Only difference is that split performs the action from the left i.e. looks for the occurrence of the separator from the left unlike rsplit that looks for occurrences from the right.
Application:
Output:
37. splitlines()
Returns a list of strings by splitting the string at line breaks and returns a list of strings that were lines in the original string.
Syntax:
Parameters:
- Keepends(optional): if provided and is true, also returns line breaks in the list of lines. By default line breaks are not included in the list returned.
Application:
Output:
Check out this article to learn more about splitlines() in Python.
38. startswith()
Returns true if a string starts with a specific string prefix. If not, returns false.
Syntax:
Parameters:
- Prefix(optional): string or tuple of strings to be checked.
- Start(optional): starting index within the string where prefix is to be checked.
- end(optional): end index within the string until which prefix is to be checked. Application:
Output:
Check out this article to know more about startswith() in Python.
39. strip()
Returns a string by removing both trailing and leading characters from the string. (what character is removed depends on the parameter provided)
Syntax:
Parameters:
charactersToBeRemoved(Optional): determines the set of characters to be considered while removing trailing and leading characters. If not provided space is considered as the only character to be removed.
Application:
Output:
40. swapcase()
Returns a string by swapping the case of the original string’s characters i.e. lower case alphabets are swapped with its upper case alphabets and visa-versa.
Syntax:
Application:
Output:
Want to learn more about swapcase() function in Python Click here.
41. title()
Returns a title-cased string by converting the first character of each word to uppercase and remaining characters of each word to lowercase of the original string.
Syntax:
Note: this operator also converts the first alphabet after every special character or number.
Application:
Output:
Check out this article to learn more about title() in Python.
42. translate()
Returns a string by replacing each character with its corresponding character provided in the mapping table that has mapping of each character (that is to be replaced) and its corresponding replacement.
Syntax:
Application:
Output:
Check out this article to learn more about translate() in Python.
43. upper()
Returns a string by converting each lower case to upper case alphabets.
Syntax:
Application:
Output:
To know more about upper() in python Click here.
44. zfill()
The zfill() in Python returns a string with character ‘0’ padded or concatenated to the left.
Syntax:
Parameters:
Width: it denotes the length of the new string that is to be returned.
NOTE: if a string starts with ‘+’ or ‘-’, the 0 are added after these symbols.
Application:
Output: