獲取子字符串周圍的字符數半徑 (Get set number radius of characters around substring)


問題描述

獲取子字符串周圍的字符數半徑 (Get set number radius of characters around substring)

在 Python 中,如何在子字符串周圍獲得一定數量的字符?

例如,這是我的字符串:

string='Mad Max: Fury Road'

假設我想添加四個字符從 'ax: Fur' 兩邊,進入輸出,所以它會是 'ad Max: Fury Ro'

如果要查找的子字符串是 string 中的 'Fury Road',那麼輸出將是 'ax: Fury Road',它會忽略它右側沒有可添加的內容。


參考解法

方法 1:

str.partition comes in really handy here:

def get_sub(string, sub, length):
    before, search, after = string.partition(sub)
    if not search:
        raise ValueError("substring not found")
    return before[‑length:] + sub + after[:length]

You could also just return before in the if statement instead of raising a ValueError. That would return the string unchanged. Usage:

print(get_sub("Mad Max: Fury Road", "Fury Road", 4))
#ax: Fury Road
print(get_sub("Mad Max: Fury Road", "Fu", 4))
#ax: Fury R

方法 2:

you could also get the string before and after the substring with .split() then return parts of both:

def get_sub_and_surrounding(string,sub,length):
    before,after = string.split(sub,1) #limit to only one split
    return before[‑length:] + sub + after[:length]

it is worth noting that in this case if sub is not actually a substring then the first line will raise a ValueError

but you can get the exact indexes for splitting it up like this:

def get_sub_and_surrounding(string,sub,length):
    i_start = string.index(sub) #index of the start of the substring
    i_end = i_start + len(sub) #index of the end of the substring (one after)

    my_start = max(0, i_start ‑length)
    # ^prevents use of negative indices from counting
    # from the end of the string by accident

    my_end = min(len(string), i_end+length) #this part isn't actually necessary, "a"[:100] just goes to the end of the string

    return string[my_start : my_end]

In this case string.index(sub) will raise a ValueError if sub is not in string.

(by Shane SmiskolzondoTadhg McDonald‑Jensen)

參考文件

  1. Get set number radius of characters around substring (CC BY‑SA 2.5/3.0/4.0)

#Python #find #substring






相關問題

如何從控制台中導入的文件中訪問變量的內容? (How do I access the contents of a variable from a file imported in a console?)

在 python 3.5 的輸入列表中添加美元符號、逗號和大括號 (Adding dollar signs, commas and curly brackets to input list in python 3.5)

為 KeyError 打印出奇怪的錯誤消息 (Strange error message printed out for KeyError)

django 1.9 中的 from django.views.generic.simple import direct_to_template 相當於什麼 (What is the equivalent of from django.views.generic.simple import direct_to_template in django 1.9)

查詢嵌入列表中的數組 (Querying for array in embedded list)

如何在 Python 中搜索子字符串是否在二進製文件中? (How to search if a substring is into a binary file in Python?)

為什麼要避免 while 循環? (Why avoid while loops?)

使用python的json模塊解析json請求 (Parse a json request using json module of python)

為什麼使用 py2app 模塊創建 mac 文件時出現錯誤? (Why i am getting Error when creating mac file using py2app module?)

當 python 線程在網絡調用(HTTPS)中並且發生上下文切換時會發生什麼? (What happens when the python thread is in network call(HTTPS) and the context switch happens?)

如何繪製一條帶斜率和一個點的線?Python (How to plot a line with slope and one point given? Python)

Pickle 找不到我不使用的模塊? (Pickle can't find module that I am not using?)







留言討論