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构建图像分类识别器的方法

机器学习用在图像识别是非常有趣的话题。 我们可以利用OpenCV强大的功能结合机器学习算法实现图像识别系统。 首先,输入若干图像,加入分类标记。利用向量量化方法将特征点进行聚类,并得出中...

tensorflow实现简单逻辑回归

逻辑回归是机器学习中很简答的一个栗子,这篇文章就是要介绍如何使用tensorflow实现一个简单的逻辑回归算法。 逻辑回归可以看作只有一层网络的前向神经网络,并且参数连接的权重只是一个值...

python使用电子邮件模块smtplib的方法

python使用电子邮件模块smtplib的方法

Smptp类定义:smtplib.SMTP(host[,port[,local_hostname[,,timeout]]]),作为SMTP的构造函数,功能是与smtp服务器建立连接,在连...

将Dataframe数据转化为ndarry数据的方法

train_comb 为Dataframe数据: train_comb= train_comb.as_matrix() #得到values的ndarry train_comb =...

Python使用sorted排序的方法小结

Python使用sorted排序的方法小结

本文实例讲述了Python使用sorted排序的方法。分享给大家供大家参考,具体如下: # 例1. 按照元素出现的次数来排序 seq = [2,4,3,1,2,2,3] # 按次数排...