Python去除字符串两端空格的方法

yipeiwu_com5年前Python基础

目的

  获得一个首尾不含多余空格的字符串

方法

可以使用字符串的以下方法处理:

string.lstrip(s[, chars])
Return a copy of the string with leading characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the beginning of the string this method is called on.

string.rstrip(s[, chars])
Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.

string.strip(s[, chars])
Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

 

具体的效果如下:

复制代码 代码如下:

In [10]: x='     Hi,Jack!        '

In [11]: print '|',x.lstrip(),'|',x.rstrip(),'|',x.strip(),'|'
| Hi,Jack!         |      Hi,Jack! | Hi,Jack! |

其中提供的参数chars用来删除特定的符号,注意空格并没有被移除,例如:

复制代码 代码如下:

In [12]: x='yxyxyxxxyy Hello xyxyxyy'

In [13]: print x.strip('xy')
 Hello

相关文章

Python 一行代码能实现丧心病狂的功能

Python 一行代码能实现丧心病狂的功能

手头有 109 张头部 CT 的断层扫描图片,我打算用这些图片尝试头部的三维重建。基础工作之一,就是要把这些图片数据读出来,组织成一个三维的数据结构(实际上是四维的,因为每个像素有 RG...

Python CSV模块使用实例

举几个例子来介绍一下,Python 的 CSV模块的使用方法,包括,reader, writer, DictReader, DictWriter.register_dialect 一直非...

利用python实现在微信群刷屏的方法

利用python实现在微信群刷屏的方法

hello,我是小小炽,这是我写的第一篇博客,写博客一直都想在写,但是苦于能力尚浅,在各位大牛面前那既然是关公面前耍大刀了,但是其实想来每一个大牛不也是从一个小白慢慢进步学习从而达到一定...

python如何对实例属性进行类型检查

本文实例为大家分享了python对实例属性进行类型检查的具体代码,供大家参考,具体内容如下 案例: 在某项目中,我们实现了一些类,并希望能像静态语言那样对他们的实例属性进行类型检查 &n...

python搜索指定目录的方法

本文实例讲述了python搜索指定目录的方法。分享给大家供大家参考。具体分析如下: #------------------------------------- # Nam...