python:rstrip一个确切的字符串,尊重顺序 [英] python: rstrip one exact string, respecting order

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

问题描述

是否可以使用 python 命令 rstrip 以便它只删除一个确切的字符串而不单独删除所有字母?

这件事发生时我很困惑:

>>>"Boat.txt".rstrip(".txt")>>>'蟒蛇'

我的预期是:

>>>"Boat.txt".rstrip(".txt")>>>'船'

我能否以某种方式使用 rstrip 并遵守顺序,以便获得第二个结果?

解决方案

您使用了错误的方法.使用 str.replace 代替:

<预><代码>>>>"Boat.txt".replace(".txt", "")'船'

注意:str.replace 将替换字符串中的任何位置.

<预><代码>>>>"Boat.txt.txt".replace(".txt", "")'船'

要仅删除最后一个尾随 .txt,您可以使用 regular表达:

<预><代码>>>>进口重新>>>re.sub(r"\.txt$", "", "Boat.txt.txt")'船.txt'

如果你想要没有扩展名的文件名,os.path.splitext 更合适:

<预><代码>>>>os.path.splitext("Boat.txt")('船', '.txt')

Is it possible to use the python command rstrip so that it does only remove one exact string and does not take all letters separately?

I was confused when this happened:

>>>"Boat.txt".rstrip(".txt")
>>>'Boa'

What I expected was:

>>>"Boat.txt".rstrip(".txt")
>>>'Boat'

Can I somehow use rstrip and respect the order, so that I get the second outcome?

解决方案

You're using wrong method. Use str.replace instead:

>>> "Boat.txt".replace(".txt", "")
'Boat'

NOTE: str.replace will replace anywhere in the string.

>>> "Boat.txt.txt".replace(".txt", "")
'Boat'

To remove the last trailing .txt only, you can use regular expression:

>>> import re
>>> re.sub(r"\.txt$", "", "Boat.txt.txt")
'Boat.txt'

If you want filename without extension, os.path.splitext is more appropriate:

>>> os.path.splitext("Boat.txt")
('Boat', '.txt')

这篇关于python:rstrip一个确切的字符串,尊重顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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