##language:zh ''' 文章来自《Python cookbook》. 翻译仅仅是为了个人学习,其它商业版权纠纷与此无关! ''' -- Zoom.Quiet [[[DateTime(2004-08-11T17:36:45Z)]]] [[TableOfContents]] = 从一个string的尾部清除空格 = 3.5 Trimming Space from the Ends of a String 从一个string的尾部清楚空格 Credit: Luther Blissett == 问题 Problem == You need to work on a string without regard for any extra leading or trailing spaces a user may have typed. 你需要工作在一个sring上,它不用关心任何额外的可能是用户打印的前导或者尾部空格。 == 解决 Solution == That's what the lstrip, rstrip, and strip methods of string objects are for. Each takes no argument and returns the starting string, shorn of whitespace on either or both sides: string对象的lstrip, rstrip, 和strip的方法就是做这个的。每个方法不带参数并且返回在一端或者两端修剪过的空格开始的字符串。 {{{ >>> x = ' hej ' >>> print '|', x.lstrip(), '|', x.rstrip(), '|', x.strip( ), '|' | hej | hej | hej | }}} == 讨论 Discussion == Just as you may need to add space to either end of a string to align that string left, right, or center in a field of fixed width, so may you need to remove all whitespace (blanks, tabs, newlines, etc.) from either or both ends. Because this is a frequent need, Python string objects supply this functionality through their methods. 就想你需要在一个固定宽度的字段上为一个string的尾部增加空格去排列它靠左,靠右或者中间一样,你或许需要从一端或者两端移除所有的 空格(blanks, tabs, newlines等)。因为这是经常需要的。python的string对象通过他们的方法提供了这个功能。 == 参考 See Also == The Library Reference section on string methods; Java Cookbook Recipe 3.12.