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中pandas的series合并方法

如下所示: In [3]: import pandas as pd In [4]: a = pd.Series([1,2,3]) In [5]: b = pd.Series(...

python 判断参数为Nonetype类型或空的实例

Nonetype和空值是不一致的,可以理解为Nonetype为不存在这个参数,空值表示参数存在,但是值为空 判断方式如下: if hostip is None: print...

selenium 安装与chromedriver安装的方法步骤

selenium 安装与chromedriver安装的方法步骤

安装 selenium可以直接可以用pip安装。 pip install selenium chromedriver的安装一定要与Chrome的版本一致,不然就不起作用(不要问我是...

pandas数值计算与排序方法

以下代码是基于python3.5.0编写的 import pandas food_info = pandas.read_csv("food_info.csv") # --------...

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

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