Python去掉字符串中空格的方法

WBOY
Release: 2016-06-16 08:44:54
Original
1898 people have browsed it

我们经常在处理字符串时遇到有很多空格的问题,一个一个的去手动删除不是我们程序员应该做的事情,今天这篇技巧的文章脚本之家就来给大家讲一下,如何用Python去除字符串中的空格。
我们先创建一个左右都有N个空格的字符串变量s,看代码:

复制代码 代码如下:
>>> s = “   脚本之家    ”
>>>
去除字符串空格,在Python里面有它的内置方法,不需要我们自己去造轮子了。
lstrip:删除左边的空格
这个字符串方法,会删除字符串s开始位置前的空格。
复制代码 代码如下:
>>> s.lstrip()
'脚本之家   '
rstrip:删除右连的空格
这个内置方法可以删除字符串末尾的所有空格,看下面演示代码:
复制代码 代码如下:
>>> s.rstrip()
'    脚本之家'
strip:删除两端的空格
有的时候我们读取文件中的内容,每行2边都有空格,能不能一次性全部去掉呢,字符符有一个内置的strip()方法可以做到。
复制代码 代码如下:
>>> s = “   脚本之家    ”
>>> s.strip()
'脚本之家'
脚本之家提示:大家可以用 dir(str) 这个方法,获得 str字符串的所有方法名单。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!