使用 Python 從字串中移除子字串列表


Python 是一種非常有用的軟體,被世界各地的人們廣泛使用,以根據其個人需求執行許多不同的功能。它用於許多不同的目的,例如資料科學、機器學習、Web 開發以及執行不同的自動化流程。它具有許多不同的功能,可以幫助我們執行上述任務,但由於 Python 中存在如此多的功能,使用者也必須面對問題。使用者面臨的一個常見問題是從字串中移除子字串。很多時候,還需要從一個主字串中移除多個子字串。在本文中,我們將學習如何使用 Python 從字串中移除子字串列表。

移除子字串的不同方法

replace 函式

這是一種從字串中移除子字串的非常簡單的方法。藉助 replace() 函式,只需定義要保留的字串和要移除的子字串,我們就可以輕鬆地移除不需要的子字串。讓我們舉個例子來說明: -

def extra_substrings(main_string, remove_substrings): #Defining the format of string and substring
    for remove_substring in remove_substrings:
        main_string = main_string.replace(remove_substring, "")  #For any substring having substring within it
    return main_string

示例

def extra_substrings(main_string, remove_substrings): #Defining the format of string and substring
    for remove_substring in remove_substrings:
        main_string = main_string.replace(remove_substring, "")  #For any substring having substring within it
    return main_string
whole_string = "Hello, everyone! This is a extra string just for example."
remove_substrings = ["everyone", "extra", "just"]  #These are the substrings which are to be removed with the help of replace() function
new_String = extra_substrings(whole_string, remove_substrings) #The extra_substring checks each of the defined substrings and removes them from the string
print(new_String)

輸出

上述程式碼的輸出如下

Hello, ! This is a  string  for example.  

re 模組

在此過程中,將使用 re 模組從主文字中提取子字串。Python 使用 re 模組來處理正則表示式。為了定義子字串並將其從字串中刪除,我們將使用 re 模組的 re.sub() 方法設計一個模式。此方法的程式碼如下所示

import re  #Do not forget to import re or else the code will not run correctly

def extra_substrings(main_string,remove_substrings):  #The string and substring are taken as argument by extra_substring
    pattern = "|".join(map(re.escape, remove_substrings)) #The | will act as a separator in the pattern that is defined
    return re.sub(pattern, "", main_string)   # The re.sub() function will be used to replace all the substring in the pattern with an empty place

示例

讓我們舉個上述程式碼的例子,使其更清晰

import re  #Do not forget to import re or else the code will not run correctly

def extra_substrings(main_string,remove_substrings):  #The string and substring are taken as argument by extra_substring
    pattern = "|".join(map(re.escape, remove_substrings)) #The | will act as a separator in the pattern that is defined
    return re.sub(pattern, "", main_string)   # The re.sub() function will be used to replace all the substring in the pattern with an empty place
whole_string = "Hello, everyone! This is a extra string just for example."
remove_substrings = ["everyone", "extra", "just"]

new_string = extra_substrings(whole_string, remove_substrings)  #The argument will remove all the words defined within substrings
print(new_string)

輸出

上述程式碼的輸出如下

Hello, ! This is a string for example.

列表推導式

這是另一種從主字串中移除子字串的極其簡單的方法。在定義子字串之前,我們可以向函式提供字串和子字串引數。列表推導式將檢查主文字的每個元件,並刪除程式碼中找到的任何子字串。此方法的程式碼如下所示

def extra_substrings(main_string, remove_substrings): 
    words = main_string.split()  # Split the string into words
    useful_words = [word for word in words if all(sub not in word for sub in remove_substrings)]   #With the help of all() function, list comprehension will check all the elements in the string and all the defined substrings will be removed
    return ' '.join(useful_words)

示例

讓我們舉個使用上述程式碼的例子,使其更清晰

def extra_substrings(main_string, remove_substrings): 
    words = main_string.split()  # Split the string into words
    useful_words = [word for word in words if all(sub not in word for sub in remove_substrings)]   #With the help of all() function, list comprehension will check all the elements in the string and all the defined substrings will be removed
    return ' '.join(useful_words)
whole_string = "Hello, everyone! This is a extra string just for example."
remove_substring = ["everyone", "extra", "just"]

new_string = extra_substrings(whole_string, remove_substring)
print(new_string)

輸出

上述程式碼的輸出如下

Hello, ! This is a string for example.

translate 函式

在此方法中,我們將使用 translate 函式從主字串中移除子字串。translate 函式返回包含翻譯表中指定的元素的字串,並將它們替換為空字串。建立翻譯表以移除子字串的程式碼如下所示

def remove_substrings_translate(main_string, remove_substrings):
    translation_table = str.maketrans("", "", "".join(remove_substrings)) #str.maketrans() is used to create the translational table 
    return main_string.translate(translation_table)  #str.translate() is used to remove the substrings with the help of translational table

示例

讓我們舉個使用上述程式碼的例子,以便更清楚地理解它

def remove_substrings_translate(main_string, remove_substrings):
    translation_table = str.maketrans("", "", "".join(remove_substrings)) #str.maketrans() is used to create the translational table 
    return main_string.translate(translation_table)  #str.translate() is used to remove the substrings with the help of translational table
whole_string = "Hello, world! This is a sample string."
remove_substrings = ["world", "sample"]
new_string = remove_substrings_translate(whole_string, remove_substrings)
print(new_string)

輸出

上述程式碼的輸出如下

H, ! Thi i   ting.

re 模組與函式結合使用

這是一種複雜的方法,用於使用者需要更多靈活性的情況。我們將使用 re.sub() 函式並建立一個另一個個性化的自定義函式,該函式允許我們決定要替換的子字串。結合使用 re.sub() 和自定義函式的程式碼如下所示

import re #Do not forget to import re or else error might occur

def extra_substrings(main_string, remove_substrings):  #Defining the arguments
    pattern = "|".join(map(re.escape, remove_substrings))
    
    def replacement(match): #Custom Function to define the substring with an empty string
        return ""
    
    return re.sub(pattern, replacement, main_string)  #re.sub() to remove the substring defined by custom function replacement()

示例

讓我們舉個使用上述程式碼的例子,以便更清楚地理解它

import re #Do not forget to import re or else error might occur

def extra_substrings(main_string, remove_substrings):  #Defining the arguments
    pattern = "|".join(map(re.escape, remove_substrings))
    
    def replacement(match): #Custom Function to define the substring with an empty string
        return ""
    
    return re.sub(pattern, replacement, main_string)  #re.sub() to remove the substring defined by custom function replacement()
whole_string = "Hello, everyone! This is a extra string just for example."
remove_substrings = ["everyone", "extra", "just"]

new_string = extra_substrings(whole_string, remove_substrings)
print(new_string)

輸出

上述程式碼的輸出如下

Hello, ! This is a string for example.

結論

如果使用者沒有采用正確的方法,那麼從字串中移除子字串的過程可能會變得令人沮喪。這是使用者經常遇到的一個問題,因此必須遵循正確的步驟。使用者可以參考本文中提供的不同方法,使用 Python 從主字串中移除子字串。

更新於: 2023年8月1日

152 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.