簡體   English   中英

如何在 python 中獲取字符串 x 之后的所有內容

[英]How to get everything after string x in python

我有一個字符串:

s3://tester/test.pdf

我想排除s3://tester/所以即使我有s3://tester/folder/anotherone/test.pdf我在s3://tester/之后得到了整個路徑

我曾嘗試使用 split & partition 方法,但我似乎無法得到它。

目前正在嘗試:

string.partition('/')[3]

但是我收到一個錯誤,說它超出了索引。

編輯:我應該指定存儲桶的名稱並不總是相同,所以我想確保它只在第三個“/”之后抓取任何東西。

你試過.replace嗎?

你可以這樣做:

string = "s3://tester/test.pdf"
string = string.replace("s3://tester/", "")
print(string)

這將用空字符串""替換"s3://tester/"

或者,您可以使用.split而不是.partition

你也可以試試:

string = "s3://tester/test.pdf"
string = "/".join(string.split("/")[3:])
print(string)

您可以使用str.split()

path = 's3://tester/test.pdf'
print(path.split('/', 3)[-1])

Output:

test.pdf

更新:使用正則表達式:

import re
path = 's3://tester/test.pdf'
print(re.split('/',path,3)[-1])

Output:

test.pdf

回答“如何在 python 中獲得 x 個字符后的所有內容”

string[x:]

請查看更新

ORIGINAL使用內置的re模塊。

p = re.search(r'(?<=s3:\/\/tester\/).+', s).group()

該模式使用lookbehind 跳過您希望忽略的部分並匹配其后的任何和所有字符,直到整個字符串被使用,將匹配的組返回給p變量以進行進一步處理。

此代碼適用於您在問題中提供的顯式s3://tester/架構之后的任何長度路徑。

更新

剛看到更新,呵呵

把這根棍子弄錯了,我的錯。

無論 S3 變量如何,下面的re方法都應該工作,在字符串中的第三個/之后返回所有內容。

p = ''.join(re.findall(r'\/[^\/]+', s)[1:])[1:]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM