3 ways to trim a String in Python

3 Ways To Trim A Python String

What do you mean by trimming a string and how can you trim a string in Python? When you remove the whitespace around strings of text, in technical terms we call it trimming a string. In this article, we’ll cover 3 methods to trim a string in Python.


Technique 1: The strip() to Trim a String in Python

Python string.strip() function basically removes all the leading as well as trailing spaces from a particular string. Thus, we can use this method to completely trim a string in Python.

Syntax:

string.strip(character)
  • character: It is an optional parameter. If passed to the strip() function, it would remove the particular passed character from both the ends of the string.

Example:

inp_str = "     Python@JournalDev"
print("Input String:")
print(inp_str)
res = inp_str.strip()
print("\nString after trimming extra leading and trailing spaces:")
print(res)

Output:

Input String:
     Python@JournalDev

String after trimming extra leading and trailing spaces:
Python@JournalDev

Example 2:

inp_str = "@@Python JournalDev@@@@"
print("Input String:")
print(inp_str)
res = inp_str.strip('@')
print("\nString after trimming extra leading and trailing spaces:")
print(res)

In the above snippet of code, we have passed ‘@‘ as the character to the strip() function to be trimmed from both ends.

Output:

Input String:
@@Python JournalDev@@@@

String after trimming extra leading and trailing spaces:
Python JournalDev

NumPy strip() method

Python NumPy module has in-built numpy.core.defchararray.strip() method that functions similar to Python string.strip() function.

This method can be used to trim a string in Python that is embedded within an array or any other iterable.

Syntax:

numpy.core.char.strip(array, chars=value)
  • array: The input array on which the trimming has to be performed.
  • chars: It is an optional parameter. If passed to the numpy.strip() function, trims the particular character from both the ends of every element of the array.

Example:

import numpy

arr = numpy.array([' JournalDev', 'Python  '])
print("Input Array:")
print(arr)
res = numpy.char.strip(arr)
print("Array after performing strip():")
print(res)

Output:

Input Array:
[' JournalDev' 'Python  ']
Array after performing strip():
['JournalDev' 'Python']

Example 2:

import numpy

arr = numpy.array([' JournalDev', 'Python  '])
print("Input Array:")
print(arr)
res = numpy.char.strip(arr, chars='Python')
print("Array after performing strip():")
print(res)

Output:

Input Array:
[' JournalDev' 'Python  ']
Array after performing strip():
[' JournalDev' '  ']

Technique 2: Python lstrip()

Python string.lstrip() function trims all the leading white-spaces from a particular input string.

Syntax:

string.lstrip(character)
  • character: It is an optional parameter. If passed to the lstrip() function, it would remove the particular passed character from the beginning of the input string.

Example:

inp_str = "    Python@JournalDev  **"
print("Input String:")
print(inp_str)
res = inp_str.lstrip()
print("\nString after trimming Extra leading spaces:")
print(res)

Output:

Input String:
    Python@JournalDev  **

String after trimming Extra leading spaces:
Python@JournalDev  **

Example 2:

inp_str = "****Python@JournalDev*"
print("Input String:")
print(inp_str)
res = inp_str.lstrip("*")
print("\nString after trimming Extra leading characters:")
print(res)

As seen above, the lstrip() function trims ‘*‘ only from the front portion of the leading portion of the input string.

Output:

Input String:
****Python@JournalDev*

String after trimming Extra leading characters:
Python@JournalDev*

NumPy lstrip() method

Python NumPy module has numpy.core.defchararray.lstrip() method that serves the same functionality as of string.lstrip() function.

This function trims all the leading spaces or particular character from every element of the input array.

Syntax:

numpy.char.lstrip(array, chars=value)

Example 1:

import numpy

arr = numpy.array(['@@!JournalDev', '@%*Python  '])
print("Input Array:")
print(arr)
res = numpy.char.lstrip(arr, chars="!%@*")
print("Array after performing lstrip():")
print(res)

Output:

Input Array:
['@@!JournalDev' '@%*Python  ']
Array after performing lstrip():
['JournalDev' 'Python  ']

Example 2:

import numpy

arr = numpy.array(['  JournalDev', ' Python'])
print("Input Array:")
print(arr)
res = numpy.char.lstrip(arr)
print("Array after performing lstrip():")
print(res)

Output:

Input Array:
['  JournalDev' ' Python']
Array after performing lstrip():
['JournalDev' 'Python']

Technique 3: Python rstrip()

Python string.rstrip() method removes all the trailing spaces from a particular input string.

Syntax:

string.rstrip(character)
  • character: It is an optional parameter. If passed to the rstrip() function, it removes the passed character from the end of the input string.

Example:

inp_str = "Python@JournalDev   "
print("Input String:")
print(inp_str)
print("Length of Input String:")
print(len(inp_str))
res = inp_str.rstrip()
print("\nString after trimming Extra trailing spaces:")
print(res)
print("Length of Input String after removing extra trailing spaces:")
print(len(res))

We have used string.len() function to get the length of the string before and after trimming. This helps us understand that the extra white-spaces from the end has been trimmed.

Output:

Input String:
Python@JournalDev   
Length of Input String:
20

String after trimming Extra trailing spaces:
Python@JournalDev
Length of Input String after removing extra trailing spaces:
17

Example 2:

inp_str = "Python@JournalDev****"
print("Input String:")
print(inp_str)
print("Length of Input String:")
print(len(inp_str))
res = inp_str.rstrip("*")
print("\nString after trimming Extra trailing characters:")
print(res)
print("Length of Input String after removing extra trailing spaces:")
print(len(res))

Output:

Input String:
Python@JournalDev****
Length of Input String:
21

String after trimming Extra trailing characters:
Python@JournalDev
Length of Input String after removing extra trailing spaces:
17

NumPy rstrip() method

Python NumPy module has numpy.core.defchararray.rstrip(array, chars) method to remove all the trailing white-spaces from every element of the input array.

Syntax:

numpy.char.rstrip(array, chars=value)

Example:

import numpy

arr = numpy.array(['  JournalDev  ', ' Python    '])
print("Input Array:")
print(arr)
res = numpy.char.rstrip(arr)
print("Array after performing rstrip():")
print(res)

Output:

Input Array:
['  JournalDev  ' ' Python    ']
Array after performing rstrip():
['  JournalDev' ' Python']

Example 2:

import numpy

arr = numpy.array(['  JournalDev****', ' Python!!'])
print("Input Array:")
print(arr)
res = numpy.char.rstrip(arr, chars="*!")
print("Array after performing rstrip():")
print(res)

In the above example, we have passed ‘*!‘ to the numpy.rstrip() function as characters to be trimmed. These characters are trimmed from the rear end of every element of the array.

Output:

Input Array:
['  JournalDev****' ' Python!!']
Array after performing rstrip():
['  JournalDev' ' Python']

Python trim string at a glance!

  • To trim a string in Python means the removal of extra white spaces or a particular group of characters from the beginning and end of the input string.
  • You can trim a string in Python using three built-in functions: strip() , lstrip(), rstrip() methods respectively.
  • Python string.strip() method removes the white-spaces from the front and back end of a particular string.
  • The string.lstrip() method removes all the leading white-spaces from a string.
  • The string.rstrip() method trims all the trailing white-spaces from a string.

Conclusion

Thus, in this article, we have understood the different ways to trim a string in Python.


References

  • Python trim string – JournalDev