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:
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.
2. lstrip(): lstrip() function returns a copy of the string after removing leading whitespaces, which means from the left of the string.
3. rstrip(): rstrip() function returns a copy of the string after removing trailing whitespaces, which means from the right of the string.
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:
Python program to illustrate strip() functionality.
# 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==' ':
out_str1 += i
print("output string 1 :(", out_str1, ")is of", len(out_str1), "characters")
print("Method 2 : using replace()")
return s.replace(' ' , '')
out_str2 = remove_spaces(string)
print("output string 2 :(", out_str2, ")is of", len(out_str2), "characters" )
# 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" )
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.
Python program to illustrate the working of lstrip() and rstrip() functions.
string = " Python trim functions "
print("Input string(", string, ") is of", len(string), "characters")
# lsrtip() removes leading spaces
print("Illustartion of lsrip()")
ostring1 = string.lstrip()
print("output string 1:", ostring1)
print("'", ostring1, "'", "length :", len(ostring1))
# rstrip() removes trailing spaces
print("Illustartion of rsrip()")
ostring2 = string.rstrip()
print("output string 2:", ostring2)
print("'", ostring2, "'", "length :", len(ostring2))
- 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.
Illustration of strip([chars]), lstrip([char]) and rstrip([char]) when optional parameter [char] is specified
# 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("strip()--> * will be removed from both ends")
str1 = string.strip('*')
print('length :', len(str1), 'chars')
print("lstrip()--> leading * from the string will be removed")
str2 = string.lstrip('*')
print('length :', len(str2), 'chars')
print("rstrip()--> trailing * from the string will be removed")
str3 = string.rstrip('*')
print('length :', len(str3), 'chars')
- 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.
Extracting sub domain name from a given 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:
- 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.
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.
This is a guide to Python Trim String. Here we discuss the introduction, examples, and why Trim String is used in Python? You may also have a look at the following articles to learn more –