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爬虫方法: 首先要掌握一些有关爬虫的基础知识,基本的要知道什么是爬虫?为什么要爬虫?数据是从哪里得来的...

使用Python进行体育竞技分析(预测球队成绩)

使用Python进行体育竞技分析(预测球队成绩)

今天我们用python进行体育竞技分析,预测球队成绩 一. 体育竞技分析的IPO模式 : 输入I(input):两个球员的能力值,模拟比赛的次数(其中,运动员的能力值,可以通过发球方赢得...

Python中os和shutil模块实用方法集锦

复制代码 代码如下:# os 模块os.sep 可以取代操作系统特定的路径分隔符。windows下为 '\\'os.name 字符串指示你正在使用的平台。比如对于Wi...

Python使用内置json模块解析json格式数据的方法

Python使用内置json模块解析json格式数据的方法

本文实例讲述了Python使用内置json模块解析json格式数据的方法。分享给大家供大家参考,具体如下: Python中解析json字符串非常简单,直接用内置的json模块就可以,不需...

利用Python进行图像的加法,图像混合(附代码)

利用Python进行图像的加法,图像混合(附代码)

一、图像的加法 图像相加可以直接利用numpy模块进行相加,也可以采用opencv里面函数进行相加, 注意事项:相加的图像类型、大小必须相同 具体代码如下: # -*- codin...