Python 字串切片:檢查字串能否透過遞迴刪除變為空
在本教程中,我們將編寫一個程式來檢查給定的字串能否透過使用切片遞迴刪除字元而變為空。讓我們看一個例子來更清楚地理解它。
輸入
string = "tutorialstutorialspointpoint" sub_string = "tutorialspoint"
輸出
True
- 第一次迭代後,**tutorialstutorialspointpoint** 變為 **tutorialspoint**。
- 第二次迭代後,字串將為空。
我們可以使用字串的 **find()** 方法實現此結果。請按照以下步驟編寫程式。
- 初始化 **字串** 和 **子字串**。
- 如果兩者中任何一個為空,則返回 **False**
- 當 **字串** 長度大於零時,執行以下操作。
- 檢查 **子字串** 是否存在於 **字串** 中。
- 如果不存在,則返回 **False**
- 返回 **True**,因為迴圈沒有在中間終止。
示例
def is_valid(string, sub_string): # checking the lengths of string and sub_string if len(string) > 0 and len(sub_string): # iterating until string becomes empty while len(string) > 0: # finding the sub_string in string index = string.find(sub_string) # checking whether its present or not if index == -1: # returning false return False # removind the sub_string string = string[0: index] + string[index + len(sub_string):] # returning True return True else: # returning False return False if __name__ == '__main__': # initializing the string and string string = 'tutorialstutorialspointpoint' sub_string = 'tutorialspoint' # invoking the method print(is_valid(string, sub_string))
輸出
如果您執行以上程式碼,則將獲得以下結果。
True
結論
如果您在本教程中有任何疑問,請在評論區提出。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP