编写一个程序,该程序接受用户输入字符串并输出每隔一个字

问题描述 投票:0回答:4

请输入一句话:快速的棕色狐狸跳过懒狗。

输出:棕色跳狗

我一直在用python中的字符串学习,但不管我做什么,我似乎无法编写一个程序来删除每个句子的第二个字母。

word=(input ("enter setence"))

del word[::2]

print(word[char], 
end="")

Print("\n")

这是我最接近的尝试。至少我能够在命令提示符下写句子,但无法获得所需的输出。

python string output word
4个回答
3
投票
string = 'The quick brown fox jumps over the lazy dog.'
even_words = string.split(' ')[::2]

您使用空格分割原始字符串,然后使用[:: 2]拼接从其中获取每个其他单词。


0
投票

尝试类似的东西:

" ".join(c for c in word.split(" ")[::2])


0
投票

试试这个:

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)

0
投票

尝试类似的东西。

sentence = input("enter sentence: ") words = sentence.split(' ') print(words[::2])

© www.soinside.com 2019 - 2024. All rights reserved.