Python Cookbook 1.5 去掉字符串两边的空格

问题:
需要过滤掉输入字符串的前导,后续空格或其它字符.这在处理用户输入的时候比较有用.

解决方法:
lstrip, rstrip, 和 strip 方法,没有参数:
>>> x = ' hej '
>>> print '|', x.lstrip( ), '|', x.rstrip( ), '|', x.strip( ), '|'
| hej | hej | hej |


另外,这三个方法还可以接受一个参数,用于过滤指定的字符组成的串 ,如:
>>> x = 'xyxxyy hejyx yyx'
>>> print '|'+x.strip('xy')+'|'
| hejyx |

需要注意的是:hejyx前面有一个空格,因为空格前的所有的x,y都被过滤掉了,而hej后面的yx没有被过滤掉,是因为执行到hejyx后面那个空格的时候就完成了.如果我们只需要留下'hej',输入下面的语句即可:

>>> print x.strip('xy ')
hej

相关说明:

lstrip(...)
S.lstrip([chars]) -> string or unicode

Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping

rstrip(...)
S.rstrip([chars]) -> string or unicode

Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping

strip(...)
S.strip([chars]) -> string or unicode

Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值