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单向链表的实现

浅谈Python单向链表的实现

链表由一系列不必在内存中相连的结构构成,这些对象按线性顺序排序。每个结构含有表元素和指向后继元素的指针。最后一个单元的指针指向NULL。为了方便链表的删除与插入操作,可以为链表添加一个表...

浅析PyTorch中nn.Module的使用

torch.nn.Modules 相当于是对网络某种层的封装,包括网络结构以及网络参数和一些操作 torch.nn.Module 是所有神经网络单元的基类 查看源码 初始化部分:...

Python列表(list)所有元素的同一操作解析

Python列表(list)所有元素的同一操作解析

针对很普遍的每个元素的操作会遍历每个元素进行操作。 这里给出了几种写法,列表每个元素自增等数学操作同理; 示例:整形列表ilist加1个数、元素类型转字符串: ilist = [1,...

Django的session中对于用户验证的支持

用户与Authentication 通过session,我们可以在多次浏览器请求中保持数据, 接下来的部分就是用session来处理用户登录了。 当然,不能仅凭用户的一面之词,我们就相...

python 实现删除文件或文件夹实例详解

python 实现删除文件或文件夹           最近自己学习Python 的知识,自己学...