Introduction to Python Trim String
String is a sequence of characters. The character can be any letter, digit, whitespace character or any special symbols. Strings in Python are immutable, which means once created, it cannot be modified. However, we can make a copy of the string and can perform various operations on it. For this, Python provides a separate class “str” for string handling and manipulations. One such operation is to remove whitespace characters from the start and/or end of the string called Trim. We can remove whitespace character using loops, but Python provides a built-in function to make this task easier.
Python provides three different Trim functions:
- strip()
- rstrip()
- lstrip()
Syntax:
1. strip(): strip() function returns a copy of the string after removing spaces from both left and right of the string, i.e. both leading and trailing whitespaces are removed.
string_object.strip([chars])
2. lstrip(): lstrip() function returns a copy of the string after removing leading whitespaces, which means from the left of the string.
string_object.lstrip([chars])
3. rstrip(): rstrip() function returns a copy of the string after removing trailing whitespaces, which means from the right of the string.
string_object.rstrip([chars])
In all the three syntaxes mentioned above, [char] is an optional parameter. If it is not provided, then by default, whitespace characters (spaces, tabs, newline chars) are removed. But if an optional parameter [char] is provided in the function, then matching characters will be removed from the string.
Why Trim String is used in Python?
- We do not always get clean data as data is collected from disparate sources.
- Data is often noisy, and String Trim is one of the ways to clean the data so that it can be manipulated efficiently.
Examples of Python Trim String
Given below are the examples of Python Trim String:
Example #1
Python program to illustrate strip() functionality.
Code:
# Traditional way to remove whitespaces from the given string
print("-------------- Method 1 : using loops-------------->")
string = ' Python '
print("length of input string :", string, '-->', len(string))
# output string
out_str1 = ""
# for loop to remove whitespaces
for i in string:
if i==' ':
pass
else :
out_str1 += i
print("output string 1 :(", out_str1, ")is of", len(out_str1), "characters")
print('\n')
print("-------------- Method 2 : using replace()-------------->")
def remove_spaces(s):
return s.replace(' ' , '')
out_str2 = remove_spaces(string)
print("output string 2 :(", out_str2, ")is of", len(out_str2), "characters" )
print('\n')
# removing whitesspaces using built-in function
print("-------------- Method 3 : using strip()-------------->")
out_str3 = string.strip()
print("output string 3 :(", out_str3, ")is of", len(out_str3), "characters" )
Output:
Explanation:
In this example, three ways are used to remove white spaces from the input string “python”.
- Using for loop: Length of the input string is printed, which includes spaces as well. The input string is then traversed using for loop. For each character, if space ‘ ‘ is found, we pass a null statement, i.e. on the encounter of a space, nothing will happen. But if the character is not in space, then it will be concatenated to output string “out_str1”.Finally, the length of out string is printed.
- Using string built-in function replace(): Here, we have defined a function which will take a string as its argument and return a copy of this string replacing a space ‘ ‘ with a null string using built-in function replace()
- Using strip() function: Last but not the least strip() function is used. It is called on the input string without any parameters. So by default, both leading and trailing spaces are removed.
Example #2
Python program to illustrate the working of lstrip() and rstrip() functions.
Code:
string = " Python trim functions "
print("Input string(", string, ") is of", len(string), "characters")
# lsrtip() removes leading spaces
print('\n')
print("Illustartion of lsrip()")
ostring1 = string.lstrip()
print("output string 1:", ostring1)
print("'", ostring1, "'", "length :", len(ostring1))
print('\n')
# rstrip() removes trailing spaces
print("Illustartion of rsrip()")
ostring2 = string.rstrip()
print("output string 2:", ostring2)
print("'", ostring2, "'", "length :", len(ostring2))
Output:
Explanation:
- In the above example, lstrip() and rstrip() functions are called on input string without specifying any optional parameters. So by default, spaces will be removed.
- The total length (number of chars) of the original string and trimmed strings are printed.
Example #3
Illustration of strip([chars]), lstrip([char]) and rstrip([char]) when optional parameter [char] is specified
Code:
# strip([chars]), lstrip([char]) and rstrip([char]) when optiona parameter [char] is specified
string = '********Python Trim String**********'
print('Input String', string)
print('length :', len(string), 'chars')
print('\n')
print("strip()--> * will be removed from both ends")
str1 = string.strip('*')
print(str1)
print('length :', len(str1), 'chars')
print('\n')
print("lstrip()--> leading * from the string will be removed")
str2 = string.lstrip('*')
print(str2)
print('length :', len(str2), 'chars')
print('\n')
print("rstrip()--> trailing * from the string will be removed")
str3 = string.rstrip('*')
print(str3)
print('length :', len(str3), 'chars')
Output:
Explanation:
- In the above example, all three trimmed functions strip(), lstrip() and rstrip() takes an optional parameter ‘*’.strip(*) removes both leading and trailing ‘*’ from the given input string.
- While lstrip() and rstrip() have removed leading and trailing ‘*’ respectively.
- The length of the input string and trimmed strings are then printed.
Example #4
Extracting sub domain name from a given list of URls using strip() function
Code:
# Program to extract sub domain name from a list of URLs using strip() function
# Input list containing different URLs
urls = ['www.facebook.com', 'www.yatra.com', 'www.youtube.com']
print("sub domains:")
for url in urls:
print(url.strip('w.com'))
Output:
Explanation:
- Input list containing different URLs is defined
- for loop is used to traverse the list. On each list item, i.e. a url, strip() is called, which will remove ‘www.’ and ‘.com’ a part from the urls as shown above.
Conclusion
String trim is useful for cleaning of data as data is collected from different sources and is always noisy and messy. strip(), lstrip() and rstrip() are the three built-in functions provided by the Python “str” class which helps in string trimming. Though this can be achieved using various traditional ways, these functions make this task a lot easier.
Recommended Articles
We hope that this EDUCBA information on “Python Trim String” was beneficial to you. You can view EDUCBA’s recommended articles for more information.