[英]How do I replace a string in a phrase in Python
這是我寫的。 有人可以幫忙嗎?
def replace(phrase):
replaced = ""
for word in phrase:
if word == ("what"):
replaced = replaced + "the"
else:
replaced = replaced + word
return replaced
print(replace(input("enter a phrase: ")))
嘗試替換方法:
def replace(phrase):
replaced = phrase.replace("what","the")
return replaced
在這里,我們使用 .split() 將您的短語按空格分開。 結果,您會得到每個單詞的列表 ['hi', 'what', 'world']。 如果你不拆分它,你將循環遍歷每個字符,如果字符串代替並且沒有字符永遠等於“什么”
def replace(phrase):
phrase = phrase.split()
replaced = ""
for word in phrase:
if word == ("what"):
replaced = replaced + " the "
else:
replaced = replaced + word
return replaced
print(replace(input("enter a phrase: ")))
你可以試試這個代碼,希望對你有幫助
def replace(phrase):
phrase = phrase.split()
replaced = ""
for word in phrase:
if word == ("what"):
replaced = replaced + " the"
else:
replaced = replaced +" "+ word
return replaced[1:]
print(replace(input("enter a phrase: ")))
輸出是:
enter a phrase: where what this what when ,
where the this the when ,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.