请输入一句话:快速的棕色狐狸跳过懒狗。
输出:棕色跳狗
我一直在用python中的字符串学习,但不管我做什么,我似乎无法编写一个程序来删除每个句子的第二个字母。
word=(input ("enter setence"))
del word[::2]
print(word[char],
end="")
Print("\n")
这是我最接近的尝试。至少我能够在命令提示符下写句子,但无法获得所需的输出。
string = 'The quick brown fox jumps over the lazy dog.'
even_words = string.split(' ')[::2]
您使用空格分割原始字符串,然后使用[:: 2]拼接从其中获取每个其他单词。
尝试类似的东西:
" ".join(c for c in word.split(" ")[::2])
试试这个:
sentenceInput=(input ("Please enter sentence: "))
# Function for deleting every 2nd word
def wordDelete(sentence):
# Splitting sentence into pieces by thinking they're seperated by space.
# Comma and other signs are kept.
sentenceList = sentence.split(" ")
# Checking if sentence contains more than 1 word seperated and only then remove the word
if len(sentenceList) > 1:
sentenceList.remove(sentenceList[1])
# If not raise the exception
else:
print("Entered sentence does not contain two words.")
raise Exception
# Re-joining sentence
droppedSentence = ' '.join(sentenceList)
# Returning the result
return droppedSentence
wordDelete(sentenceInput)
尝试类似的东西。
sentence = input("enter sentence: ")
words = sentence.split(' ')
print(words[::2])