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 SQLAlchemy的Mapping与Declarative详解

前面介绍过vSQLAlchemy中的 Engine 和 Connection,这两个对象用在row SQL (原生的sql语句)上操作,而 ORM(Object Relational M...

python中eval与int的区别浅析

python中eval和int的区别是什么?下面给大家介绍一下: 1.eval()函数 eval(<字符串>)能够以Python表达式的方式解析并执行字符串,并将返回结果输出...

django框架模板中定义变量(set variable in django template)的方法分析

本文实例讲述了django框架模板中定义变量的方法。分享给大家供大家参考,具体如下: 总有一些情况,你会想在django template中设置临时变量,但是django 对在模板中对临...

基于python实现从尾到头打印链表

这篇文章主要介绍了基于python实现从尾到头打印链表,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 题目描述 输入一个链表,按链表...

python中property和setter装饰器用法

python中property和setter装饰器用法

作用:调用方法改为调用对象, 比如 : p.set_name() 改为 p.set_name 区别:前者改变get方法,后者改变set方法 效果图: 代码: class Pers...