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

相关文章

django表单实现下拉框的示例讲解

方法一: queue = forms.ModelChoiceField(label=u'队列',queryset=Queue.objects.all()) 方法二: clas...

特征脸(Eigenface)理论基础之PCA主成分分析法

特征脸(Eigenface)理论基础之PCA主成分分析法

在之前的博客 人脸识别经典算法一:特征脸方法(Eigenface)里面介绍了特征脸方法的原理,但是并没有对它用到的理论基础PCA做介绍,现在做补充。请将这两篇博文结合起来阅读。以下内容大...

Python字符串和文件操作常用函数分析

本文实例分析了Python字符串和文件操作常用函数。分享给大家供大家参考。具体如下: # -*- coding: UTF-8 -*- ''' Created on 2010-12-2...

计算机二级python学习教程(2) python语言基本语法元素

计算机二级python学习教程(2) python语言基本语法元素

上一篇:计算机二级Python学习笔记(一) 其实昨天Python并没有安装成功,打开就报错: 于是今天先解决这个问题,搜了一下api-ms-win-crt-process- 1-1-...

Python调用Windows API函数编写录音机和音乐播放器功能

Python调用Windows API函数编写录音机和音乐播放器功能

功能描述: 1)使用tkinter设计程序界面; 2)调用Windows API函数实现录音机和音乐播放器。 参考代码: ​ 运行界面: ​ 总结 以上所述是小...