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之有容乃大的list(2)

对list的操作 合并list 《有容乃大的list(1)》中,对list的操作提到了list.append(x),也就是将某个元素x 追加到已知的一个list后边。 除了将元素追加到l...

node.js获取参数的常用方法(总结)

1、req.body 2、req.query 3、req.params 一、req.body例子 body不是nodejs默认提供的,你需要载入body-parser中间件才可以使用re...

Centos Python2 升级到Python3的简单实现

1. 从Python官网到获取Python3的包, 切换到目录/usr/local/src #wget https://www.python.org/ftp/python/3.5.1...

Opencv-Python图像透视变换cv2.warpPerspective的示例

Opencv-Python图像透视变换cv2.warpPerspective的示例

Opencv-Python图像透视变换cv2.warpPerspective 代码如下: # -*- coding:utf-8 -*- import cv2 import numpy...

在OpenCV里使用特征匹配和单映射变换的代码详解

在OpenCV里使用特征匹配和单映射变换的代码详解

前面已经学习特征查找和对应匹配,接着下来在特征匹配之后,再使用findHomography函数来找出对应图像的投影矩阵。首先使用一个查询图片,然后在另外一张图片里找到目标对象,其实就是想...