简体   繁体   English

如何在一行上输出首字母缩略词

[英]How do I output the acronym on one line

I am following the hands-on python tutorials from Loyola university and for one exercise I am supposed to get a phrase from the user, capatalize the first letter of each word and print the acronym on one line.我正在学习 Loyola 大学的 Python 实践教程,对于一个练习,我应该从用户那里得到一个短语,将每个单词的第一个字母大写,并将首字母缩略词打印在一行上。

I have figured out how to print the acronym but I can't figure out how to print all the letters on one line.我已经弄清楚如何打印首字母缩写词,但我无法弄清楚如何在一行上打印所有字母。

    letters = []
    line = input('?:')
    letters.append(line)
    for l in line.split():
        print(l[0].upper())

Your question would be better if you shared the code you are using so far, I'm just guessing that you have saved the capital letters into a list.如果您共享目前使用的代码,您的问题会更好,我只是猜测您已将大写字母保存到列表中。

You want the string method .join(), which takes a string separator before the .您需要字符串方法 .join(),它在 .join() 之前需要一个字符串分隔符。 and then joins a list of items with that string separator between them.然后用它们之间的字符串分隔符连接一个项目列表。 For an acronym you'd want empty quotes对于首字母缩略词,您需要空引号

eg例如

l = ['A','A','R','P']
acronym = ''.join(l)
print(acronym)

Pass end='' to your print function to suppress the newline character, viz:end=''传递给您的print函数以抑制换行符,即:

for l in line.split():
    print(l[0].upper(), end='')
print()

You could make a string variable at the beginning string = "" .您可以在开头创建一个字符串变量string = ""

Then instead of doing print(l[0].upper()) just append to the string string += #yourstuff然后,而不是做print(l[0].upper())只是附加到字符串string += #yourstuff

Lastly, print(string)最后, print(string)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM