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中的Descriptor描述符学习教程

Descriptor是什么?简而言之,Descriptor是用来定制访问类或实例的成员的一种协议。额。。好吧,一句话是说不清楚的。下面先介绍一下Python中成员变量的定义和使用。 我们...

对python3.4 字符串转16进制的实例详解

如下所示: def str_to_hex(s):     s = s.split(' ')     send_buf =...

Windows中使用wxPython和py2exe开发Python的GUI程序的实例教程

Windows中使用wxPython和py2exe开发Python的GUI程序的实例教程

Python是支持可视化编程,即编写gui程序,你可以用它来编写自己喜欢的桌面程序。使用wxPython来做界面非常的简单,只是不能像C#一样拖动控件,需要自行写代码布局。在完成编写之后...

Python基于回溯法子集树模板解决最佳作业调度问题示例

Python基于回溯法子集树模板解决最佳作业调度问题示例

本文实例讲述了Python基于回溯法子集树模板解决最佳作业调度问题。分享给大家供大家参考,具体如下: 问题 给定 n 个作业,每一个作业都有两项子任务需要分别在两台机器上完成。每一个作业...

python模拟登陆阿里妈妈生成商品推广链接

淘宝官方有获取商品推广链接的API,但该API属于增值API 普通开发者没有调用权限 需要申请开通 备注:登陆采用的是阿里妈妈账号登陆非淘宝账号登陆 复制代码 代码如下:#coding:...