Python 如何获取字符前的所有内容以及字符后的x数量?

Python 如何获取字符前的所有内容以及字符后的x数量?,python,split,Python,Split,这是反复试验,似乎无法得到我想要的 我正在访问API以获取一些信息。不幸的是,它是唯一一个获取该信息的API,为此,它下载文件的二进制内容并命名为: folder\filename.whatever i、 e.test\purpleMonkeyTest.docx 电话中还有很多信息,但有一行: Saved the binary content to: /home/user/python/test\purpleMonkeyTest.docx 有些文件具有“或其他特殊字符,因此我不能仅获取文件名并

这是反复试验,似乎无法得到我想要的

我正在访问API以获取一些信息。不幸的是,它是唯一一个获取该信息的API,为此,它下载文件的二进制内容并命名为:

folder\filename.whatever
i、 e.
test\purpleMonkeyTest.docx

电话中还有很多信息,但有一行:

Saved the binary content to: /home/user/python/test\purpleMonkeyTest.docx
有些文件具有
或其他特殊字符,因此我不能仅获取文件名并将其作为脚本的一部分删除,因为我不知道要转义什么

因此,我的目标是脱线并获得:

/home/user/python/test\purpleMonkeyTest.docx
然后只获得:

/home/user/python/test\pu
然后:

我认为通配符应该适用于所有人,除非有更好的方法。所有保存的文件中都有字符
\
,因此我已经得到了在
\
之前的所有内容,但我也希望在这之后有一个或两个字符

以下是我尝试过的:

def fileName(itemID):
    import fnmatch
    details = itemDetails(itemID, True) # get item id and file details
    filepath = matchPattern((details), 'Saved the binary content to: *')
    filepath = (filepath).split('\\')[0]
    print(filepath)
    #os.remove(re.escape(filepath))
    return (matchPattern((details), 'Binary component: *'))


def matchPattern(details, pattern):
    import fnmatch
    return (fnmatch.filter((details), pattern)[0].split(": " ,1)[1])
输出:

/home/user/python/test
purpleMonkeyTest.docx
我确实希望以后再使用这个文件名:这实际上是主要目标。不过API会自动下载这个该死的文件

编辑:

下面的答案适用于获取我想要的字符。不过Os remove并没有删除该文件

OSError: [Errno 2] No such file or directory: '/home/user/python/test\\Re*'
我猜os.remove不支持Wilds,是通过glob实现的

    files = glob.glob((filepath)+"*")
    for file in files:
     os.remove(file)

谢谢您的帮助!!

据我所知,您希望检索两部分内容-第一部分
/
\
之间的所有内容,之后是两个字符,然后是
\
之后的所有内容:

str = "Saved the binary content to: /home/user/python/test\purpleMonkeyTest.docx"

print (str[str.index("/"):str.rindex("\\") + 3])
print (str[str.rindex("\\") + 1:])
输出

/home/user/python/test\pu

purpleMonkeyTest.docx

str = "Saved the binary content to: /home/user/python/test\purpleMonkeyTest.docx"

print (str[str.index("/"):str.rindex("\\") + 3])
print (str[str.rindex("\\") + 1:])