2010-12-04 56 views
12

在Python中,如何創建給定字符串的首字母縮略詞?在Python中創建首字母縮略詞

一樣,輸入字符串:

'First Second Third' 

輸出:

'FST' 

我想是這樣的:

>>> for e in x: 
     print e[0] 

但它不工作...如何任何建議這可以做到嗎?我確信有這樣做的適當方式,但我似乎無法弄清楚。我必須使用re嗎?

回答

11

嘗試

print "".join(e[0] for e in x.split()) 

你居然循環遍歷所有字符字符串x英寸如果您想循環使用單詞,可以使用x.split()

+0

的「分裂」這裏是這是在原來失蹤的相關位。 – 2010-12-04 18:52:57

+2

只需兩秒鐘的差距,所以爲你+1! – user225312 2010-12-04 18:52:58

+0

謝謝,我確實想過使用這個,但不知何故我堅持自己的解決方案。 – user225312 2010-12-04 18:58:09

5

沒有re

>>> names = 'Vincent Vega Jules Winnfield' 
>>> ''.join(x[0] for x in names.split()) 
'VVJW' 
2
s = 'First Second Third' 
x = s.split(' ') 
for e in x: 
    print e[0] 

應該做的伎倆。你

2

也可以使用

re.split('\W')

拆就非單詞字符行/文本。這可能會更強大一點。

3

現在的東西有點不同......

words = "There ain't no such thing as a free lunch." 
acronym = ''.join(word[0] for word in words.upper().split()) 
print acronym 
# TANSTAAFL 

TANSTAAFL是一個相當-熟悉一個,BTW)。

13

如果你想使用資金只有

>>>line = ' What AboutMe ' 
>>>filter(str.isupper, line) 
'WAM' 

什麼可能不被領先的上限的話。

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

怎麼樣只有上限的話。

>>>line = ' GNU is Not Unix ' 
>>>''.join(w[0] for w in line.split() if w[0].isupper()) 
'GNU' 
2

如果你想要做的事情,是語法正確的(無論區域設置)的方式,使用title(),然後filter()

acronym = filter(str.isupper, my_string.title()) 

title()是相當真棒;它會根據語言環境對字符串進行分類並且是正確的。

0

這裏是如何做到的縮寫與正則表達式,留下數字作爲是:

import re 
words = "internet explorer 10" 
print re.sub(r"([a-zA-Z])[a-z,A-Z]+\s*",r"\1",words).upper() 

IE10

相關問題