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

yipeiwu_com6年前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的多线程在io方面比单线程还是有优势,但是在多线程开发时,少不了对文件的读写操作。在管理多个线程对同一文件的读写操作时,就少不了文件锁了。 使用fcntl 在linux下,p...

Python绘制频率分布直方图的示例

Python绘制频率分布直方图的示例

项目中在前期经常要看下数据的分布情况,这对于探究数据规律非常有用。概率分布表示样本数据的模样,长的好不好看如果有图像展示出来就非常完美了,使用Python绘制频率分布直方图非常简洁,因为...

Python实现监控Nginx配置文件的不同并发送邮件报警功能示例

Python实现监控Nginx配置文件的不同并发送邮件报警功能示例

本文实例讲述了Python实现监控Nginx配置文件的不同并发送邮件报警功能。分享给大家供大家参考,具体如下: 因为项目中经常涉及到多个Nginx之间的配置文件更改,可能回导致最后Ngi...

深入讲解Python函数中参数的使用及默认参数的陷阱

C++里函数可以设置缺省参数,Java不可以,只能通过重载的方式来实现,python里也可以设置默认参数,最大的好处就是降低函数难度,函数的定义只有一个,并且python是动态语言,在同...

Django在pycharm下修改默认启动端口的方法

Django在pycharm下修改默认启动端口的方法

如题,度娘前几条答案说的都不清不楚,俺来补上: 点击下拉选项中的Edit Configuration进入如下界面: 如果左侧没有出现django server,说明您的项目是不dja...