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使用opencv驱动摄像头的方法

如下所示: #coding:utf-8 import cv2 import sys from PIL import Image def CatchUsbVideo(win...

为Python的web框架编写前端模版的教程

为Python的web框架编写前端模版的教程

虽然我们跑通了一个最简单的MVC,但是页面效果肯定不会让人满意。 对于复杂的HTML前端页面来说,我们需要一套基础的CSS框架来完成页面布局和基本样式。另外,jQuery作为操作DOM的...

关于Python 的简单栅格图像边界提取方法

在GIS中,栅格属性里有关于栅格自身的信息,背景(nodata value)对于识别一张图像的边界像元尤为重要,我们目的只要把每行每列中的第一次出现不是nodata的像元和最后一次出现n...

python利用有道翻译实现"语言翻译器"的功能实例

python利用有道翻译实现"语言翻译器"的功能实例

实例如下: import urllib.request import urllib.parse import json while True: content = input(...

使用go和python递归删除.ds store文件的方法

python版本:复制代码 代码如下:#!/usr/bin/env pythonimport os, sys;def walk(path):  print "cd directory:"...