问题:
需要过滤掉输入字符串的前导,后续空格或其它字符.这在处理用户输入的时候比较有用.
解决方法:
lstrip, rstrip, 和 strip 方法,没有参数:
>>> x = ' hej '
>>> print '|', x.lstrip( ), '|', x.rstrip( ), '|', x.strip( ), '|'
| hej | hej | hej |
另外,这三个方法还可以接受一个参数,用于过滤指定的字符组成的串 ,如:
>>> x = 'xyxxyy hejyx yyx'
>>> print '|'+x.strip('xy')+'|'
| hejyx |
需要注意的是:hejyx前面有一个空格,因为空格前的所有的x,y都被过滤掉了,而hej后面的yx没有被过滤掉,是因为执行到hejyx后面那个空格的时候就完成了.如果我们只需要留下'hej',输入下面的语句即可:
>>> print x.strip('xy ')
hej
相关说明:
lstrip(...)
S.lstrip([chars]) -> string or unicode
Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
rstrip(...)
S.rstrip([chars]) -> string or unicode
Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
strip(...)
S.strip([chars]) -> string or unicode
Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
分享到:
相关推荐
PythonCookbook3高清.pdf
这是 Python Cookbook 英文版的,需要的拿走吧
Python Cookbook(第3版)中文版.pdf 极清PDF
绍了Python应用在各个领域中的一些使用技巧和方法,从最基本的字符、文件序列、字典和排序,到进阶的面向对象编程、数据库和数据持久化、XML处理和Web编程,再到比较高级和抽象的描述符、装饰器、元类、迭代器和生成...
python cookbook(第3版)高清中文完整版.pdf,作者: David Beazley, Brian K. Jones 译者: 熊能 版本: 第3版 出版社: O’Reilly Media, Inc. 出版日期: 2013年5月08日 Copyright © 2013 David Beazley and ...
Modern Python Cookbook
python cookbook(第3版)高清中文完整版
Python Cookbook, 2nd Edition, Python Cookbook, 2nd Edition, Python Cookbook, 2nd Edition
Python Cookbook.pdf
Modern Python Cookbook 英文无水印pdf pdf使用FoxitReader和PDF-XChangeViewer测试可以打开
python cookbook 3th python cookbook 3th python cookbook 3th python cookbook 3th
PythonCookbook.zip
Python CookBook 3rd Edition, epub type file
python cook book 3th 中文版及英文版。 这本书的目标读者是那些想深入理解 Python 语言机制和最新编程技能的资深程序员。很多讨论都是标准库,框架和应用程序使用到的高级技术。... --- 摘至 python cookbook 3th
这本独特的食谱包含了用Python 3.3编写和测试的实用食谱,适合有经验的Python程序员,他们希望专注于现代工具和习惯用法。
Python Cookbook 第二版 完整示例代码,Python Cookbook 第二版 完整示例代码
《Python Cookbook》第二版英文版的epub格式,可以用移动设备或者kindle等电纸书阅读
Python Cookbook(第三版)中文,Python Cookbook(第三版)中文,Python Cookbook(第三版)中文
python cookbook 中文版,欢迎python爱好者进行下载,谢谢
Maya Programming with Python Cookbook 英文azw3 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除