Python String Functions

Python String Functions

Python string functions open many ways to perform some really useful operations on a string. We have already discussed about Python String Formatting in the previous section.

There are a lot of functions that can be used to perform various operations on a string. It is counter-productive to remember and understand all of them. Therefore, only the most important string functions are explained with examples in this tutorial.

The functions which are less used in daily coding life is explained briefly at the end of the page.

Most Useful Python String Functions

Let’s discuss about the Python String functions widely used in daily coding life.

1. split() function

split() function splits the string into a list of multiple substrings using the delimiter. The default delimiter is a whitespace, therefore this function can be used without passing any parameter.

Syntax: split(separator, maxsplit)

The parameter maxsplit decides the maximum number of occurrences on which split is performed. Default value of this parameter is “-1” which means the function will split the string on all occurrences of the delimiter.

Example

Python String Functions - split()

2. join() function

join() function joins all the objects in an iterable. It takes one parameter – iterable.

Syntax: join(iterable)

The string that is used to access this method acts as the separator between two joined objects from the iterable.

Example

Python String Functions - join()

Let’s understand the code:

For the string1 variable, we used asterisk (*) as the separator in the string. In the next variable, string2, we went for the most common separator, i.e., a whitespace.

Bonus Tips

join() function is the opposite of split() function. These two functions help a lot in basic competitive programming.

3. strip() function

strip() function removes all the whitespaces from both sides of a string. strip() takes an optional parameter “[chars]” which is a powerful tool that removes all the specified characters from the string.

Syntax: strip([chars])

Let’s understand strip() function with the help of an example.

Example

Python String Functions - strip() - 1

strip() function without any parameter by default removed all the whitespaces on both the sides but that will not be enough as there is still too much clutter left in our string.

To remove everything except the substring “Hello”, you can pass a parameter in the function as below.

Example

Python String Functions - strip() - 2

The parameter contains the characters that we want to remove.

The strip() function now leads us to lstrip() and rstrip(). As the name suggests, lstrip() removes the characters from the left side and rstrip() removes the characters from the right side. Consider this for an example:

Example

Python String Functions - strip() - 3

4. format() function

format() function formats some set of values into a placeholder present in a string. As a parameter, format() takes values that need to be formatted into the placeholders.

Syntax: format(val1, val2, val3, …)

Example

Python String Functions - format()

The curly brackets in the original string acts as a placeholder.

5. lower() and upper() function

Using lower() and upper() functions, a string can be converted into lowercase or uppercase respectively. Both of these functions do not take any parameter whatsoever.

Example

Python String Functions - lower() and upper()

6. replace() function

replace() function replaces a string with another string.

Syntax: replace(old, new, count)

replace() function has two mandatory parameters – old and new.

  • old is the old string that needs to be replaced
  • new is the new string which is used to replace the old string.
  • third parameter “count” that specifies how many occurrences are going to be replaced. If this parameter is not specified, all occurrences of the specified string will be replaced.

Example

Python String Functions - replace() - 1

If there are more than one occurrence of the specified string, then all of the occurrences will be replaced with the new string unless you specify the count parameter. Let’s take a below example.

Example

Python String Functions - replace() - 2

7. find() and index() function

find() function returns the index of the sub-string that we find in the specified string. It will return -1 if the substring is not present in the string.

One necessary parameter; the string that we want to find

Two optional parameters; start and end index of the search

Syntax: find(str, start, end)

On the other hand, index()  function raises an error if the sub-string is not present in the string. Other than this dissimilarity, both these functions are quite same.

Syntax: index(str, start, end)

Let’s see both functions in action.

Example

Python String Functions - find() and index() - 1

If the value is not found, both functions act differently. Lets check it in the below example.

Example

Python String Functions - find() and index() - 2

8. translate() function

This is the last must-know Python string function. translate() function replaces characters specified in a table or in a dictionary or in a mapping table, and then returns a string.

Syntax: translate(table)

Example

Python String Functions - translate()

We used “F” to replace “L” by using their ascii codes, i.e., 70 and 76 respectively.

Other String functions

Function

Description

format_map()Similar to format(), this function returns the formatted string after replacing specific values from the mapping in the string placeholders ‘{}’.
count()Returns the number of occurrences of a specified string in another specified string.
startswith()Returns True if the string starts with the specified string. If not, then the function will return False.
endswith()Returns True if the string ends with the specified string. If not, then the function will return False.
capitalize()This function capitalizes the string and returns it. If the string has uppercase letters, then this function will convert them into lowercase.
expandtabs()We can control the number of whitespaces given by “\t” if it is present in the string.
center()This function centers the string around specified characters of the specified size and returns the string.
__contains()This function is from the Python String class and it can also be used to check if a string is present in another string.
isdigit()Returns True if every character in the string is a digit. Returns False if that is not the case.
isalnum()If the string is made of only alphanumeric characters, then this function will return True. Otherwise, it will return False.
isalpha()If the string on which this function is called contains only alphabets then this function will return True.
False will be returned if the string is not entirely made up of alphabets.
isdecimal()Returns True if every character in the string is a decimal. Returns False if that is not the case.
islower()If the string only contains lowercase letters, then this function will return True. Otherwise, returns False.
isupper()If the string only contains uppercase letters, then this function will return True. Otherwise, returns False.
isnumeric()If the string only contains numeric characters, then this function will return True, else False.
isspace()If the string on which this function is called only contains whitespaces, then the function will return True. The function will return False if that is not the case.
isprintable()There are certain characters like “\n”, “\t”, etc., that are not printable.
If all the characters in the string are printable then this function will return True otherwise, False.
lsplit()This function creates a left-justified version of the string and returns it.
rsplit()This function creates a right-justified version of the string and returns it.
swapcase()Returns a string where lowercase letters become uppercase and uppercase letters become lowercase.
title()Returns a string after converting the first letter of the string to uppercase.
swapcase()Returns a string where lowercase letters become uppercase and uppercase letters become lowercase.
istitle()Returns True if the string is in the title case. Returns False otherwise.
rfind()Returns the last position where the specified substring was found in the string.
zfill()This function fills the string with a specific number of 0s at the beginning of that string.
rindex()Returns the last position where the specified substring Python String Functions was found in the string.
splitlines()This is just like the split() function, instead, it uses a new line as the delimiter to split the string.
This function returns a list of strings where each index of the list used to be a line in the original string.
partition()This function returns a tuple where the string is split up into three parts.
maketrans()The translation table is returned upon execution of this function. The translation table can be used in translations.

Bonus Tips

  • You do not have to remember all these functions because you will not need most of them in day-to-day coding. But you might still need them at the correct time and place. You will have to practice every day to know when and where each function has to be used.
  • Read more about Python String Functions at Python’s Documentation.

Tutorials for all brains!