[英]How can I compare 2 list and remove the a string from 1 list that contain a substring from other list? Python
[英]How can I remove a substring from a string in python?
我正在為 class 做一個實驗室,我需要幫助。 我需要從給定的字符串中刪除一個字符,然后刪除剛剛刪除的字符前面的字符。 我一直在嘗試這樣做幾個小時,但我無法弄清楚。 確切的說明是:“從原始字符串中刪除所有出現的刪除字符串。每次取出刪除字符串時,您還必須刪除刪除字符串之前的字母。刪除字符串及其前導字符后,您必須檢查是否存在更多的刪除字符串。” 我已經走到這一步了,但我現在不知道該怎么辦
def removeChar(s, c, l):
count = 0
while count <= len(s):
found = s.find(c)
before = s.find(l)
new = l + 1
remove = s[found: new]
count += 1
print()
original = input("What is the original phrase: ") #s
target = input("What do you want to remove: ") #c
after = len(target) - 1
removeChar(original, target, after)
我不會為你做作業:) 但我會寫一個遞歸程序。 就像是:
def remove_substr(string, substring):
# if has substring:
# remove it
# run remove_substr() again on parsed string
# else return string
祝你運動順利!
嘗試給出一個錯誤的 output 的工作示例。 要刪除部分文本,您可以使用text[:start_delete] + text[end_delete + 1:]
或text.replace('to_delete', '')
。
像s, c, l
這樣的字符名稱很難理解,被認為是不好的做法。 給他們更多有說服力的名字,比如original, target
。
如果您確實編寫了 function,您通常希望從中return
一些內容或print
一些內容,否則您將看不到任何結果。
無論如何,這是我對練習的看法。
original = input("What is the original phrase: ") #s
target = input("What do you want to remove: ") #c
#While our target is in the string and not the very beginning
while target in original and target in original[1:]:
#assign the starting position to start and fail if it's zero
if start := original.find(target):
#keep the part before(-1) and after the text
original = original[:start-1] + original[start + len(target):]
print(original)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.