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中的二维数组的操作方法

需要在程序中使用二维数组,网上找到一种这样的用法:   #创建一个宽度为3,高度为4的数组 #[[0,0,0], # [0,0,0], # [0,0,0], # [0,...

Python实现快速排序的方法详解

本文实例讲述了Python实现快速排序的方法。分享给大家供大家参考,具体如下: 说起快排的Python实现,首先谈一下,快速排序的思路: 1、取一个参考值放到列表中间,初次排序后,让左侧...

python logging日志模块原理及操作解析

一、基本介绍 logging 模块是python自带的一个包,因此在使用的时候,不必安装,只需要import即可。 logging有 5 个不同层次的日志级别,可以将给定的 logg...

python实现验证码识别功能

python实现验证码识别功能

本文实例为大家分享了python实现验证码识别的具体代码,供大家参考,具体内容如下 1.通过二值化处理去掉干扰线 2.对黑白图片进行降噪,去掉那些单独的黑色像素点 3.消除边框上附着的黑...

Python实现CNN的多通道输入实例

CNN可以同时进行多通道的输入,例如一张彩色图片可以分解成RGB三个通道输入给CNN,当使用自己的数据集时,可以通过numpy来实现数据的多通道输入。 假设我们有两个组数据a和b:...