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

标签 python string python-2.7 strip

我在 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”)

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

最佳答案

你应该引用python documentation rstrip!

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

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

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

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

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

关于python - python 中带有字母 "l"的 rstrip 函数的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32054687/

相关文章:

c - C 中 strcat 和 strncat 函数的另一种替代方法是什么?

python - 在 Python 2 中循环两个异步生成器

python - Python 中的刽子手游戏

python - 初始化中……命令 'sox'返回了非零的退出状态2

python - 如何在 python 代码中创建文件(如果可用,则默认为文本文件)

java - java中的字符串比较解决方案不起作用

c# - 为什么 String.Clone() 返回原始字符串而不是它的副本?

python - 当最终网址为 https 时,如何使用 python 取消缩短(解析)网址?

python - 输入文本选项 : curious behavior

python - 如何在 python 中打印/返回一个类?