用Python创建首字母缩略词

use*_*312 13 python

在Python中,如何创建给定字符串的首字母缩写?

比如,输入字符串:

'First Second Third'
Run Code Online (Sandbox Code Playgroud)

输出:

'FST'
Run Code Online (Sandbox Code Playgroud)

我正在尝试这样的事情:

>>> for e in x:
        print e[0]
Run Code Online (Sandbox Code Playgroud)

但它没有工作......有关如何做到这一点的任何建议?我确信有一种正确的方法可以做到这一点,但我似乎无法弄明白.我必须使用re吗?

kev*_*pie 16

如果您只想使用大写字母

>>>line = ' What AboutMe '
>>>filter(str.isupper, line)
'WAM'
Run Code Online (Sandbox Code Playgroud)

怎么样的话可能不是领导帽.

>>>line = ' What is Up '
>>>''.join(w[0].upper() for w in line.split())
'WIU'
Run Code Online (Sandbox Code Playgroud)

只有Caps的话呢.

>>>line = ' GNU is Not Unix '
>>>''.join(w[0] for w in line.split() if w[0].isupper())
'GNU'
Run Code Online (Sandbox Code Playgroud)


Sve*_*ach 15

尝试

print "".join(e[0] for e in x.split())
Run Code Online (Sandbox Code Playgroud)

你的循环实际上循环遍历字符串中的所有字符x.如果您想循环使用单词,可以使用x.split().

  • 差不多两秒钟,所以给你+1! (2认同)

use*_*312 5

没有re:

>>> names = 'Vincent Vega Jules Winnfield'
>>> ''.join(x[0] for x in names.split())
'VVJW'
Run Code Online (Sandbox Code Playgroud)


Raf*_*ler 5

如果您想以语法正确的方式执行操作(无论区域设置如何),请使用title(), then filter()

acronym = filter(str.isupper, my_string.title())
Run Code Online (Sandbox Code Playgroud)

title()非常棒;它使字符串标题大小写,并且根据区域设置是正确的。