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

2024-10-01 07:10:26 发布

您现在位置: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

Tags: 程序is字母单词sentence句子wordvery
3条回答

python 3.8或更高版本

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

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

输出:

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

python 3.6和3.7

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)}")

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('-- {}'.format(''.join(acrostic)))

也许你在找这样的东西:

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)))

输入:

  • 在一个循环中,向用户询问一个单词,如果没有,请停止
  • 如果是一个单词,请将其保存在sentence中,并将其第一个字母保存在acrosticword[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

相关问题 更多 >