打印列表中每个项目的首字母

时间:2020-03-18 10:19:16

标签: python

我正在尝试创建一个程序,要求输入单词,直到输入“”为止。然后,程序将打印出连接在句子中的所有单词。然后,将每个单词的第一个字母设为反义词。我正在使用python。示例如下所示。先感谢您。这是真的要到期了。 :)

  • 我编写的代码:
sentence = []

acrostic = []

word = -1

while word:

     sentence.append(word)

      acrostic.append(sentence[0].upper())
print(sentence)
print("-- {}".format(acrostic))
  • 我想要代码做什么:
Word: A

Word: cross

Word: tick

Word: is

Word: very

Word: evil

Word: 

A cross tick is very evil

-- ACTIVE

5 个答案:

答案 0 :(得分:2)

输入:

  • 在一个循环中,向用户询问一个单词,如果没有什么可以停止的
  • 如果是单词,请将其保存在sentence中,并将其保存为acrostic的第一个字母(word[0]而不是sentence[0]

对于输出:

  • 该句子的各个单词之间加一个空格:" ".join(sentence)
  • 对于杂技演员,不加任何字母:"".join(acrostic)
sentence = []
acrostic = []
while True:
    word = input('Please enter a word, or enter to stop : ')
    if not word:
        break
    sentence.append(word)
    acrostic.append(word[0].upper())

print(" ".join(sentence))
print("-- {}".format("".join(acrostic)))

给予

Please enter a word, or " to stop : A
Please enter a word, or " to stop : cross
Please enter a word, or " to stop : tick
Please enter a word, or " to stop : is
Please enter a word, or " to stop : very
Please enter a word, or " to stop : evil
Please enter a word, or " to stop : 
A cross tick is very evil
-- ACTIVE

答案 1 :(得分:2)

python 3.8或更高版本

55

输出:

sentence = []
acrostic = []
while user_input := input('word: '):
    sentence.append(user_input)
    acrostic.append(user_input[0].upper())

print(' '.join(sentence))
print(f"-- {''.join(acrostic)}")

python 3.6和3.7

word: A
word: cross
word: tick
word: is
word: very
word: evil
word: 
A cross tick is very evil
-- ACTIVE

python 3.5或更早版本

sentence = []
acrostic = []
while True:
    user_input = input('word: ')
    if not user_input:
        break
    sentence.append(user_input)
    acrostic.append(user_input[0].upper())

print(' '.join(sentence))
print(f"-- {''.join(acrostic)}")

答案 2 :(得分:0)

也许您正在寻找这样的东西:

sentence = []
acrostic = []
word = -1

while word != "":
    word = input("Word: ")

    if word:
        sentence.append(word)
        acrostic.append(word[0].upper())

print(" ".join(sentence))
print("-- {}".format("".join(acrostic)))

答案 3 :(得分:0)

目标:提取每个单词的第一个字母,直到输入``''。

acrostic = ""
sentence = ""
while(True):
    word = input("enter a word= ")
    if(word!=''):
        acrostic+=word[0].upper()
        sentence+=word+" " 
    else:
        break
print(sentence)
print(acrostic)

使用您的示例输入;

enter a word= A
enter a word= cross
enter a word= tick
enter a word= is
enter a word= very
enter a word= evil
enter a word= 

输出

A cross tick is very evil
ACTIVE

答案 4 :(得分:0)

虽然每个人都涵盖了基本的循环,但这是使用iter(callable, sentinel)模式的一个很好的例子:

def initial():
    return input('Word: ')[:1]

print('-- ' + ''.join(iter(initial, '')))

会产生:

Word: A
Word: cross
Word: tick
Word: is
Word: very
Word: evil
Word: 
-- Active