How to trim a string in Python

What does trimming a string mean and how does it work in Python? In this article, we will discuss how to trim the whitespace from a string.

Trimming a string technically refers to removing the white space from within the text string. The three built-in functions strip, rstrip, lstrip, and regular expression methods in Python can be used to remove spaces from strings. To remove the space, all of these techniques require no arguments.

  • How to trim a string in Python by using the regular expression method
  • How to trim a string in Python by using the lstrip method
  • How to trim a string in Python by using the rstrip method
  • How to trim a string in Python by using the strip() method
  • How to trim a string in NumPy Python
  • How to trim a string in Pandas Python
  • How to trim a newline from a string in Python

How to trim a string in Python by using the regular expression method

  • The regex module’s ‘re’ class has the function re.sub(). To remove the whitespace from the string we can easily use this method.
  • The Python Regular Expressions (re) package contains the re.sub() method. All instances of the given pattern that match are replaced by the replace string in the returned string.
  • Python’s re.sub() function can be used to trim strings. Using the built-in function re.sub(), the string is trimmed and its leading and trailing white spaces are removed.

Syntax:

Let’s have a look at the Syntax and understand the working of the re.sub() method in Python.

re.sub(pattern, repl, string, count=0, flags=0)
  • It consists of a few parameters
    • pattern: This parameter defines the string/pattern that we want to be replaced.
    • repl: This parameter is used to define the pattern with which the pattern is replaced.
    • Count: By default, it takes a 0 value and it defines the number of replacements that should occur.

Example:

Let’s take an example and check how to trim a string in Python by using the regular expression method.

Source Code:

import re
# Input string 
Country_name = "  United States of America  "

# By using the re.sub() method
new_result = re.sub(r'^\s+|\s+$', '', Country_name)

# Display the Content
print(new_result)

As a result, we will import the re library first to verify that the function, which is found in the re module, and Then, we produce an input string called Country_name = ” United States of America “.

Now we want to remove the whitespace from the string by using the re.sub() function and within this function, we assigned the symbol \s and it denotes the whitespaces.

Here is the implementation of the following given code.

How to trim a string in Python by using the regular expression method
How to trim a string in Python by using the regular expression method

This is how to trim a string in Python by using the regular expression method.

Read: Python program for current date and time

How to trim a string in Python by using the lstrip method

  • In this section, we will discuss how to trim a string by using the lstrip method in Python.
  • A built-in Python function called lstrip() trims the left side of a string of all whitespace characters and returns the resulting new string. No arguments are taken by the lstrip() method.
  • The lstrip() method returns a copy of the string. If there is no argument given, it erases the leading whitespace by default.

Syntax:

Here is the Syntax of the lstrip() method in Python.

str.lstrip(characters)

Note: A string has been removed from the left of the string.

The example code below shows how to trim a string by using the lstrip method in Python.

# Input string
state_name_in_USA = '  Alaska,Alabama,Arizona'
print("Input string :",state_name_in_USA )

# Using replace() method
new_output= state_name_in_USA.lstrip()

# Display the content
print("After trimming the string :",new_output)

In this example, the string ” Alaska, Alabama, Arizona” is used as the input string. We removed the original string ” Alaska, Alabama, Arizona” after returning the modified string. The lstrip() function must be used in this code:

No optional parameters are passed when the lstrip() function is used on the input string. Therefore, spaces are automatically trimmed. ‘ Alaska, Alabama, Arizona’  will result from the removal of the space on the left.

You can refer to the below Screenshot

How to trim a string in Python by using the lstrip method
Remove whitespace from the left side by using the lstrip method

As you can see in the Screenshot we have discussed how to trim a string in Python by using the lstrip method.

Read: How to add zeros before a number in Python

How to trim a string in Python by using the rstrip method

  • Let us discuss How to trim a string in Python by using the rstrip method.
  • A built-in Python function called rstrip() trims the right side of a string of all whitespace characters and returns the resulting new string. No arguments are taken by the rstrip() method.
  • This is an additional technique for removing white spaces. In comparison to lstrip, rstrip() is used to remove the right side of the space and it is clear of all whitespace.

Syntax:

Here is the Syntax of the rstrip() method in Python.

str.rstrip(characters)

Note: A string has been removed from the right of the string.

Example:

Let’s take an example and check how to trim a string in Python by using the rstrip method.

Source Code:

# Input String
Cars_in_USA = "Tesla,BMW   "
print("Input string:",Cars_in_USA)

# By using the lstrip()
result = Cars_in_USA.rstrip()

# Display the Content
print("Remove white spaces:",result)

In the following given code we have created an input string named Cars_in_USA and then used the rstrip() function and this function is used to remove the whitespace from the right side of the string.

The right side of the string is free of whitespace. The output is, therefore “Tesla, BMW”. If the string contains the newline character (/n), the return character (/r), or the tab character (/t),

Here is the Screenshot of the following given code

How to trim a string in Python by using the rstrip method
Remove whitespace from the right side by using the lrstrip method

In this example, we have understood how to Remove whitespace from the right side by using the lrstrip method.

Read: Python program for binary search

How to trim a string in Python by using the strip() method

  • In this section, How to trim a string in Python by using the strip() method in Python.
  • Python has a built-in library function called strip(). By removing the leading and trailing whitespaces, letters, and symbols supplied to the strip() method, it is used to return a duplicate of the original string.
  • In other words, by passing a group of characters as an argument to the strip() method, the Python string function removes characters from the string’s left and right ends. If no input is supplied to the strip() function, it defaults to removing whitespaces from the beginning and end of the string.

Syntax:

string.strip(character)

Note: It is an optional parameter. When a character is passed to the strip() function, it is removed from both ends of the string.

Example:

Let’s take an example and check How to trim a string in Python by using the strip() method in Python.

Source Code:

# Original string
cities_of_USA = '   New York, Los Angeles, California    '
print("Input String :",cities_of_USA )

# By using str.strip() function
new_output = cities_of_USA.strip()
print(" Input String after trimming :", new_output)

In this program, we take ‘ New York, Los Angeles, California ‘ as an input string and then used the strip() function for trimming the whitespace from the input string.

Here is the implementation of the following given code

How to trim a string in Python by using the strip method
By using the strip method trimmed whitespaces from both sides

In this example, we have understood How to trim a string in Python by using the strip() method.

Read: Remove a specific character from a string in Python

How to trim a string in NumPy Python

  • Here we will discuss how to remove the whitespace from the input string in NumPy Python.
  • To perform this particular task we are going to use the numpy.char.strip() function.
  • The leading and trailing characters for each item in an array are removed using the strip() function. By default, this function trims the string of any unnecessary leading and following whitespaces unless a specific character is specified.

Syntax:

let’s have a look at the syntax and understand the working of numpy.char.strip() in Python

char.strip(a, chars=None)
  • It consists of only two parameters
    • a: This is an input array of given strings.
    • chars: The chars parameter effectively indicates a string of characters that should be deleted. Removes the whitespace by default if this argument is not given or is given as None.

Example:

Let’s take an example and check how to remove the whitespace from the input string in NumPy Python.

Source Code:

import numpy as np

# Creation of array by using the np.array()
Country_name = np.array(['   U.S.A', 'Belgium  '])
print("Input Array :", Country_name)

# By using the numpy.char.strip() function
new_output = np.char.strip(Country_name)
print(" Input Array after performing trim :",new_output )

In the following given code, we created the input array by using the np.array() function and within this function, we assigned the country name as a text string.

Now we want to trim the whitespace from the input array and for this, we are going to use the np.char.strip() function.

Here is the implementation of the following given code.

How to trim a string in NumPy Python
How to trim a string in NumPy Python

This is how to trim a string in NumPy Python.

Read: How to remove the last character from a string in Python

How to trim a string in Pandas Python

  • In this section, we will discuss how to trim a string in Python Pandas.
  • In any text data, Pandas offers three ways to deal with white spaces. As shown by the name, the functions str.lstrip() and str.rstrip() remove spaces from the left side and the right side of the text, and str.strip() removes spaces from both sides.
  • In this example, we will use the str.strip() function to trim the trailing and leading space of the column.

Let’s look at an example of how to trim the column’s leading and trailing spaces and all of its spaces.

Source Code:

import pandas as pd
import numpy as np
 
#Create a DataFrame
data_fr = {
    'Country_name':[' U.S.A ',' Germany ', ' Australia','Belgium ','Bulgaria '],
   'Country_id':[167,727443,434674,92533,325373]}
 
data_fr = pd.DataFrame(data_fr,columns=['Country_name','Country_id'])
print(data_fr)
print(data_fr['Country_name'].str.len())

data_fr['Country_name'] = data_fr['Country_name'].str.strip()
print (data_fr)
print(data_fr['Country_name'].str.len())

In the above code first, we imported the Pandas library and then created a dataframe by using the pd.DataFrame() function and within this dataframe, we assigned the country_name and country_id and check the length of the strings.

Here is the Screenshot of the following given code.

How to trim a string in Pandas Python
Trim right and left side white spaces in Pandas

This is how to trim a string in Python Pandas.

Read: How to Python Append List to Another List

How to trim a newline from a string in Python

  • In this example, we will discuss how to trim a newline from a string in Python.
  • To perform this particular task we are going to use the strip() function and the strip() function is utilized to trim leading and trailing newlines from the string. Additionally, it removes the whitespaces on each side of the string.
  • In other words, by passing a group of characters as an argument to the strip() method, the Python string function removes characters from the string’s left and right ends.

Example:

Let’s take an example and check how to trim a newline from a string in Python.

# Input String
Country_name = "\n United States of America \n"

# By using the strip() function
new_output = Country_name.strip()

# Display the Content
print(new_output)

Here is the Screenshot of the following given code

How to trim a newline from a string in Python
Remove the newline from the string

In this example, we have understood How to trim a newline from a string in Python.

Also, take a look at some more Python tutorials.

In this article, we have learned how to trim the whitespace from a string with a different method. And also we have covered the following given topics.

  • How to trim a string in Python by using the regular expression method
  • How to trim a string in Python by using the lstrip method
  • How to trim a string in Python by using the rstrip method
  • How to trim a string in Python by using the strip() method
  • How to trim a string in NumPy Python
  • How to trim a string in Pandas Python
  • How to trim a newline from a string in Python