理解python对字符串的lstrip方法 [英] Understanding python's lstrip method on strings

查看:33
本文介绍了理解python对字符串的lstrip方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个我认为是错误的问题,我正在寻求确认,或者我不了解此方法的工作原理.

这是我的基本输出:

(Pdb) x = 'KEY_K'(Pdb) x.lstrip('K')'EY_K'(Pdb) x.lstrip('KE')'Y_K'(Pdb) x.lstrip('KEY')'_K'(Pdb) x.lstrip('KEY_')''(pdb) 导入系统(Pdb) sys.version'2.7.11(默认,2015 年 12 月 5 日,14:44:47)
[GCC 4.2.1 兼容 Apple LLVM 7.0.0 (clang-700.1.76)]'

我的理解是该示例中的最后一个 'lstrip' 应该返回 'K',但它没有.有谁知道为什么?

解决方案

就在文档中:

<块引用>

lstrip(...)S.lstrip([chars]) -> 字符串或 unicode

返回删除前导空格的字符串 S 的副本.如果给出了字符而不是无,则删除字符中的字符.如果chars是unicode,S会在剥离前转成unicode

'K''KEY_' 中,这就是为什么你的最后一个例子返回 ''.

请注意,如果 'K' 前面有一个不在 'KEY_' 中的字符,则不会被删除:

<预><代码>>>>'KEY_xK'.lstrip('KEY_')'xK'

I ran into what I think is a bug, and I'm looking for confirmation or that I am not understanding how this method works.

Here's my basic output:

(Pdb) x = 'KEY_K'
(Pdb) x.lstrip('K')
'EY_K'
(Pdb) x.lstrip('KE')
'Y_K'
(Pdb) x.lstrip('KEY')
'_K'
(Pdb) x.lstrip('KEY_')
''
(Pdb) import sys
(Pdb) sys.version
'2.7.11 (default, Dec  5 2015, 14:44:47) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.1.76)]'

My understanding is that the final 'lstrip' in that example should have returned 'K', but it did not. Does anyone know why?

解决方案

It's right in the docs:

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

'K' is in 'KEY_', that's why your last example returns ''.

Note that 'K' would not have been removed if preceded by a character that is not in 'KEY_':

>>> 'KEY_xK'.lstrip('KEY_')
'xK'

这篇关于理解python对字符串的lstrip方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆