【问题标题】:Trouble with simple acronym program python简单的首字母缩写程序python的问题
【发布时间】:2020-03-03 06:58:06
【问题描述】:

我正在尝试制作一个首字母缩略词程序,用户可以在其中每行输入 1 个单词,在输入空格后,程序将输出由每个单词的第一个字母创建的单词。它在我不想要的输出后打印一个空格。关于如何删除它的任何想法?更多信息如下:

例如

User input:
Word: Hello
Word: World

Desired output:
Hello World <-- whitespace here that I don't want
-- HW

My Current Code that works:

words = []
word = input('Word: ')
while word:
  words.append(word)
  word = input('Word: ') #Word input

for word in words:

   print(word, end=" ") #displays all words on one line 

  # Printing a white space ^

# Wanting to print this code on a new line 
first_letters = ''.join([word[0] for word in words])
new=first_letters.upper()
print("\n-- " + new)

【问题讨论】:

  • 我有生成我想要的输出的代码,但它在打印用户输入的单词后会打印一个空格。关于如何删除它的任何想法?

标签: python string


【解决方案1】:

你快到了。将你所拥有的与 numprint 结合起来:

for word in words:
    print(word[:1], end="")  # Display all first letters without spaces.

【讨论】:

    【解决方案2】:

    这段代码做你想做的一切

    words = []
    word = input('Word: ')
    while word:
      words.append(word)
      word = input('Word: ') #Word input
    
    
    print(' '.join(words))
    
    
    first_letters = ''.join([word[0] for word in words])
    new=first_letters.upper()
    print("-- " + new)
    

    【讨论】:

      【解决方案3】:

      就这么简单?

      words = ['Hello','World']
      print(' '.join(w for w in words))
      print('-- '+''.join(w[0] for w in words))
      

      【讨论】:

        【解决方案4】:

        给定字符串数组words。有几种方法可以获取单词的首字母。下面很少。

        第一种方法

        first_letters = ''
        for word in words:
          first_letters += word[0]
        print(first_letters) 
        

        第二种方法

        first_letters = ''.join([word[0] for word in words])
        print(first_letters)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-30
          • 1970-01-01
          • 2012-08-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多