查找字符后的最后一个子串 [英] Find the last substring after a character

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

问题描述

我知道如何找到子字符串的很多方法:从开始索引到结束索引,在字符之间等等,但是我有一个我不知道如何解决的问题:我有一个字符串,例如路径:folder1/folder2/folder3/new_folder/image.jpg第二个路径:folder1/folder2/folder3/folder4/image2.png

从这个路径我只想取最后一部分:image.jpgimage2.png.如果我不知道子字符串何时开始(我不知道索引,但我可以假设它将在最后一个 / 字符之后),如果多次出现一个字符,我该如何获取子字符串重复 (/) 并且扩展名不同(.jpg.png 甚至其他)?

解决方案

使用 os.path.basename() 而不是担心细节.

os.path.basename() 返回路径的文件名部分:

<预><代码>>>>导入 os.path>>>os.path.basename('folder1/folder2/folder3/new_folder/image.jpg')'图像.jpg'

对于更通用的字符串拆分问题,您可以使用 str.rpartition() 在给定的字符序列上分割一个字符串从末尾算起:

<预><代码>>>>'foo:bar:baz'.rpartition(':')('foo:bar', ':', 'baz')>>>'foo:bar:baz'.rpartition(':')[-1]'巴兹'

str.rsplit() 你可以分割多次直到一个限制,再次从最后:

<预><代码>>>>'foo:bar:baz:spam:eggs'.rsplit(':', 3)['foo:bar'、'baz'、'垃圾邮件'、'鸡蛋']

最后但并非最不重要的是,您可以使用 str.rfind() 只查找子字符串的索引,从末尾搜索:

<预><代码>>>>'foo:bar:baz'.rfind(':')7

I know many ways how to find a substring: from start index to end index, between characters etc., but I have a problem which I don't know how to solve: I have a string like for example a path: folder1/folder2/folder3/new_folder/image.jpg and the second path: folder1/folder2/folder3/folder4/image2.png

And from this paths I want to take only the last parts: image.jpg and image2.png. How can I take a substring if I don't know when it starts (I don't know the index, but I can suppose that it will be after last / character), if many times one character repeats (/) and the extensions are different (.jpg and .png and even other)?

解决方案

Use os.path.basename() instead and not worry about the details.

os.path.basename() returns the filename portion of your path:

>>> import os.path
>>> os.path.basename('folder1/folder2/folder3/new_folder/image.jpg')
'image.jpg'

For a more generic string splitting problem, you can use str.rpartition() to split a string on a given character sequence counting from the end:

>>> 'foo:bar:baz'.rpartition(':')
('foo:bar', ':', 'baz')
>>> 'foo:bar:baz'.rpartition(':')[-1]
'baz'

and with str.rsplit() you can split multiple times up to a limit, again from the end:

>>> 'foo:bar:baz:spam:eggs'.rsplit(':', 3)
['foo:bar', 'baz', 'spam', 'eggs']

Last but not least, you could use str.rfind() to find just the index of a substring, searching from the end:

>>> 'foo:bar:baz'.rfind(':')
7

这篇关于查找字符后的最后一个子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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