我已经在字符串上使用.find()
来查找用户想要从字符串中删除的单词的索引,但是现在我如何使用这个索引来删除所说的单词?
功能如下:
sentence = "The quick brown fox jumps over the lazy dog."
print("The sentence is: "+ sentence)
user_removal = input("Which word would you like to remove? ")
user_removal_word = sentence.find(user_removal)
我已经使用if语句,然后格式化,然后从句子中删除单词,然后重新创建它,但我相信有一个更好的方法来做到这一点。
你可以使用切片。
使用
somestring [lowerborder: upperborder]。
sentence = "The.quick.brown.fox.jumps.over.the.lazy.dog."
print("The sentence is: "+ sentence)
user_removal = input("Which word would you like to remove? ")
lowerborder = sentence.find(user_removal) -1
upperborder = lowerborder + len(user_removal) +1
firstPart = sentence[:lowerborder]
secondPart = sentence[upperborder:]
result = firstPart + secondPart
print(result)
输入:"狐狸">
输出:The.quick.brown.jumps.over.the.lazy.dog。
方法是确定两个边界,即您试图删除的单词的起始(下界)和结束(上界)的索引。
然后生成一个新字符串(firstpart),它包含初始字符串的所有内容,直到下边界。
之后生成第二个字符串,该字符串从您要删除的单词之后开始,并包含该单词之后的所有内容。
然后把两者放在一起得到结果。单词之间的点表示输出确实只是期望的输出,因为print
语句中看不到额外的空格。
假设句子中的单词之间用一个空格分隔。然后可以使用split()
创建所有单词的列表尝试删除指定的单词。如果单词不存在,则抛出ValueError。
如果删除成功,重新加入单词列表
sentence = "The quick brown fox jumps over the lazy dog."
print(f"The sentence is: {sentence}")
user_removal = input("Which word would you like to remove? ")
words = sentence.split()
try:
words.remove(user_removal)
print(' '.join(words))
except ValueError:
print(f'Selected word "{user_removal}" is not in the sentence')
例子:
The sentence is: The quick brown fox jumps over the lazy dog.
Which word would you like to remove? jumps
The quick brown fox over the lazy dog.
The sentence is: The quick brown fox jumps over the lazy dog.
Which word would you like to remove? cat
Selected word "cat" is not in the sentence