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

相关文章

python实现决策树分类算法

python实现决策树分类算法

本文实例为大家分享了python实现决策树分类算法的具体代码,供大家参考,具体内容如下 1、概述 决策树(decision tree)——是一种被广泛使用的分类算法。 相比贝叶斯算法,决...

Python判断变量是否已经定义的方法

Python判断变量是否已经定义是一个非常重要的功能,本文就来简述这一功能的实现方法。 其实Python中有很多方法可以实现判断一个变量是否已经定义了。这里就举出最常用的两种作为示例,如...

python中print()函数的“,”与java中System.out.print()函数中的“+”功能详解

python中的print()函数和java中的System.out.print()函数都有着打印字符串的功能。 python中: print("hello,world!") 输出...

PyCharm设置护眼背景色的方法

PyCharm设置护眼背景色的方法

方法一: File->Seting->Editor-Colors->General->Text->Default text->BackGround设置...

python 去除txt文本中的空格、数字、特定字母等方法

使用场景:需要去除txt文本中的空格、数字、特定字母等。 需要修改的txt文本叫做:train.txt 修改之后保存成:train_output.txt # ecoding=utf-...