使用 python 2.7 和 3.5 的 string.strip() 中的奇怪错误 [英] Odd bug in string.strip() using python 2.7 and 3.5

查看:42
本文介绍了使用 python 2.7 和 3.5 的 string.strip() 中的奇怪错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 string.strip() 进行非常简单的字符串操作时,我得到了一些非常奇怪的结果.我想知道这是一个只影响我的问题(我的 python 安装有问题?)还是一个常见的错误?

这个错误很复杂,它在这里:

<预><代码>>>>a = './omqbEXPT.pool'>>>a.strip('./').strip('.pool')'mqbEXPT' #第一个 'o' 缺失!!!

只有在 './' 后面跟着 'o' 时才会发生!

<预><代码>>>>a = './xmqbEXPT.pool'>>>a.strip('./').strip('.pool')'xmqbEXPT'

这是怎么回事?!我已经在 python 2.7 和 3.5 上测试过这个,结果没有改变.

解决方案

strip 方法实际上是设计用来工作的.

<块引用>

chars 参数是一个字符串,指定要删除的字符集.

chars 参数不是前缀或后缀;相反,其值的所有组合都被剥离:

因此,当您说 my_string.strip('.pools') 时,它将删除该集合中的所有前导和尾随字符(即 {'.', 'p', 'o', 'l', 's'}).

您可能想要使用 str.replacere.sub.

<预><代码>>>>'./omqbEXPT.pool'.replace('./', '').replace('.pool', '')'omqbEXPT'>>>进口重新>>>re.sub(r'^\.\/|\.pool$', '', './omgbEXPT.pool')'omqbEXPT'

I am getting some very odd result on a quite simple string manipulation using string.strip(). I am wondering whether it's a problem that affects only me (something is wrong with my python installations?) or it's a common bug?

The bug is very wired and here it goes:

>>> a = './omqbEXPT.pool'
>>> a.strip('./').strip('.pool')
'mqbEXPT' #the first 'o' is missing!!!

It occurs only if an 'o' is following './' !

>>> a = './xmqbEXPT.pool'
>>> a.strip('./').strip('.pool')
'xmqbEXPT'

What's going on here?! I have tested this on both python 2.7 and 3.5 and the result doesn't change.

解决方案

This is how the strip method is actually designed to work.

The chars argument is a string specifying the set of characters to be removed.

The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

So when you say my_string.strip('.pools'), it's going to remove all leading and trailing characters in that set (ie. {'.', 'p', 'o', 'l', 's'}).

You probably want to use str.replace or re.sub.

>>> './omqbEXPT.pool'.replace('./', '').replace('.pool', '')
'omqbEXPT'

>>> import re
>>> re.sub(r'^\.\/|\.pool$', '', './omgbEXPT.pool')
'omqbEXPT'

这篇关于使用 python 2.7 和 3.5 的 string.strip() 中的奇怪错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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