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

相关文章

opencv实现静态手势识别 opencv实现剪刀石头布游戏

opencv实现静态手势识别 opencv实现剪刀石头布游戏

本文实例为大家分享了opencv实现静态手势识别的具体代码,供大家参考,具体内容如下 要想运行该代码,请确保安装了:python 2.7,opencv 2.4.9 效果如下:...

python字典DICT类型合并详解

python字典DICT类型合并详解

本文为大家分享了python字典DICT类型合并的方法,供大家参考,具体内容如下 我要的字典的键值有些是数据库中表的字段名, 但是有些却不是, 我需要把它们整合到一起, 因此有些这篇文章...

python操作MySQL数据库的方法分享

我采用的是MySQLdb操作的MYSQL数据库。先来一个简单的例子吧: 复制代码 代码如下: import MySQLdb try: conn=MySQLdb.connect(host=...

python实现在一个画布上画多个子图

python实现在一个画布上画多个子图

matplotlib 是可以组合许多的小图, 放在一张大图里面显示的. 使用到的方法叫作 subplot. 均匀画图 使用import导入matplotlib.pyplot模块, 并简写...

利用Python批量生成任意尺寸的图片

利用Python批量生成任意尺寸的图片

实现效果 通过源图片,在当前工作目录的/img目录下生成1000张,分别从1*1到1000*1000像素的图片。 效果如下: 目录结构 实现示例 # -*- coding: ut...