python 中带有字母 "l" 的 rstrip 函数的奇怪行为

Strange behaviour of rstrip function in python with letter "l"

我在 Python 2.7 中有一个程序可以处理一些字符串。如果某些字符串以字母 "l" 结尾(不是 "L",只是 "l"),rstrip 会在不应删除此 "l" 时删除它。 示例代码:

file=u'isabel.algo'#final "l"
str="/"+file+"/"+file.rstrip(".algo")+".py"
print str
file=u'isabeL.algo'#final "L"
str="/"+file+"/"+file.rstrip(".algo")+".py"
print str
file='isabel.algo'#non unicode
str="/"+file+"/"+file.rstrip(".algo")+".py"
print str

这导致:

/isabel.algo/isabe.py
/isabeL.algo/isabeL.py
/isabel.algo/isabe.py

可以看出,当"file"以"L"结束时是没有问题的。但是当以"l"结尾时,最后的字符串是错误的(应该是"isabel.py")

如有任何帮助,我们将不胜感激。提前致谢。

你应该参考rstrippython documentation!

rstrip 获取要从字符串末尾删除的字符列表。因此 file.rstrip(".algo") 将去除字符串右端的所有 '.'、'a'、'l'、'g' 和 'o' 字符。

此问题的潜在解决方法是 split 您的字符串使用“.”。作为分隔符:

str="/"+file+"/"+file.split(".")[0]+".py"

或者按照评论中建议的 chromano,您可以使用 replace 方法:

str="/"+file+"/"+file.replace(".algo",".py")