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

相关文章

numpy.linspace函数具体使用详解

numpy.linspace函数具体使用详解

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) 在指定的间隔内返回均匀间隔的数...

给Python的Django框架下搭建的BLOG添加RSS功能的教程

前些天有位网友建议我在博客中添加RSS订阅功能,觉得挺好,所以自己抽空看了一下如何在Django中添加RSS功能,发现使用Django中的syndication feed framewo...

Pycharm使用之设置代码字体大小和颜色主题的教程

Pycharm使用之设置代码字体大小和颜色主题的教程

1. File->Setting  打开如下所示的对话框,可以在Editor->General->Font下设置字体大小(Size)、行距(Line spac...

利用Python将时间或时间间隔转为ISO 8601格式方法示例

利用Python将时间或时间间隔转为ISO 8601格式方法示例

前言 大家都知道,Python自带的datetime库提供了将datetime转为ISO 8610格式的函数,但是对于时间间隔(inteval)并没有提供转换的函数,下面我们动手写一个。...

深入解析神经网络从原理到实现

深入解析神经网络从原理到实现

1.简单介绍 在机器学习和认知科学领域,人工神经网络(artificial neural network,缩写ANN),简称神经网络(neural network,缩写NN)或类神经网...