Python之去掉字符串空格(strip)

您所在的位置:网站首页 python空格函数 Python之去掉字符串空格(strip)

Python之去掉字符串空格(strip)

2023-07-23 05:46| 来源: 网络整理| 查看: 265

正文:

Python去掉字符串空格有三个函数:

strip 同时去掉字符串左右两边的空格; lstrip 去掉字符串左边的空格; rstrip 去掉字符串右边(末尾)的空格;

详细解读:

声明:s为字符串,re为要删除的字符序列

strip函数:s.strip(re) 1,用于删除s字符串中开头处、结尾处、位于re删除序列的字符 2,当re为空时,strip()默认是删除空白符(包括‘\n’,‘\r’,‘\t’,‘’),例如: >>>a = ' abc' >>>a.strip() 'abc' >>>a = '\t\t\nabc' >>>a.strip() 'abc' >>>a = ' abc\r\t' >>>a.strip() 'abc'

3,这里我们说的re删除序列是只要满足re的开头或者结尾上的字符在删除序列内,就能删除掉,比如说:

>>> a = 'abc123' >>>>a.strip('342') 'abc1' >>>a.strip('234') 'abc1'

可以看出结果是一样的。

lstrip函数:s.lstrip(re),用于删除s字符串中开头处,位于re删除序列中的字符,比如: >>>a = " this is string example.....wow!!! " >>>a.lstrip() 'this is string example.....wow!!! ' >>>a = "88888888this is string example....wow!!!8888888" >>>a.lstrip('8') 'this is string example....wow!!!8888888' rstrip函数:s.rstrip(re),用于删除s字符串中结尾处,位于re删除序列的字符,比如: >>>a = " this is string example.....wow!!! " >>>a.rstrip() ' this is string example.....wow!!!' >>>a = "88888888this is string example....wow!!!8888888" >>>a.rstrip('8') '8888888this is string example....wow!!!'

OK!到此结束啦,不知道你了解了没???^-^



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3