Goal:
1. Using the whitespace of the string module
2. Delete left, right, and white space on both sides
The code is as follows:
[email protected] python]# cat rmspace.py
#!/usr/bin/env python#Coding:utf8"""use a string to remove left and right whitespace. """ fromStringImportwhitespace#Delete the left blankdefLrmsps (ASTR): forIinchxrange (len (ASTR)):ifAstr[i] not inchwhitespace:returnAstr[i:]#when all whitespace characters are entered, NULL is returned. return "'#Delete the blank on the right and start judging from the right of the list. defRrmsps (ASTR): forIinchReversed (xrange (Len (ASTR))):ifAstr[i] not inchwhitespace:returnAstr[:(i+1)] return "'#Delete left and right sides of white spacedefRmsps (ASTR):returnRrmsps (Lrmsps (ASTR))if __name__=='__main__': Hi='Hello,world. ' Print 'Delete left blank: |%s|'%Lrmsps (HI)Print 'Delete Right blank: |%s|'%Rrmsps (HI)Print 'Delete both sides blank: |%s|'% Rmsps (HI)
2. Run the code and test the effect
[[email protected] python] # python rmspace.py Delete left blank: |hello,world. | Delete right margin:| hello,world.| Delete both sides blank:|hello,world.|
Python simulates removing whitespace on both sides of a string