REMOVE LEADING AND TRAILING CHARACTERS
Python provides the functions strip(), lstrip(), and rstrip() to remove characters in a text string. Listing 1.6 displays the content of remove1.py that shows you how to search for a string.
LISTING 1.6: remove1.py
text = ' leading and trailing white space '
print('text1:','x',text,'y')
text = text.lstrip()
print('text2:','x',text,'y')
text = text.rstrip()
print('text3:','x',text,'y')
Listing 1.6 starts by concatenating the letter x and the contents of the variable text, and then printing the result. The second part of Listing 1.6 removes the leading white spaces in the string text and then appends the result to the letter x. The third part of Listing 1.6 removes the trailing white spaces in the string text (note that the leading white spaces have already been removed) and then appends the result to the letter x.
The output from launching Listing 1.6 is here:
text1: x leading and trailing white space y text2: x leading and trailing white space y text3: x leading and trailing white space y
If you want to remove extra white spaces inside a text string, use the replace() function, as discussed in the previous section. The following example illustrates how this can be accomplished, which also contains the re module as a “preview” for what you will learn in Chapter 4:
import re
text = 'a b'
a = text.replace(' ', '')
b = re.sub('\s+', ' ', text)
print(a)
print(b)
The result is here:
ab a b
Chapter 2 shows you how to use the join() function to remove extra white spaces in a text string.