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读文件保存到字典,修改字典并写入新文件的实例

实例如下所示: tcode={} transcode={} def GetTcode(): #从文本中获取英文对应的故障码,并保存在tcode字典(故障码文本样例:oxff,0xff...

python+opencv实现霍夫变换检测直线

python+opencv实现霍夫变换检测直线

本文实例为大家分享了python+opencv实现霍夫变换检测直线的具体代码,供大家参考,具体内容如下 python+opencv实现高斯平滑滤波 python+opencv实现阈值分...

python实现zencart产品数据导入到magento(python导入数据)

python版本要求在3.3.x,需要mysql connector for python第三方库支持不适用所有的zencart导入到magento 复制代码 代码如下:#encodin...

python 列表递归求和、计数、求最大元素的实例

利用python的递归来执行求和、计数、求最大元素的方法简直溜到爆,这里粘贴一下代码: 列表的递归求和: def sum(list): if list==[]: return...

pandas DataFrame 交集并集补集的实现

pandas DataFrame 交集并集补集的实现

1.场景,对于colums都相同的dataframe做过滤的时候 例如: df1 = DataFrame([['a', 10, '男'], ['b', 11, '...