棘手的谜题,中途!读大写字母

时间:2012-09-08 03:49:11

标签: python

首先,这是我的代码:

s = raw_input("code: ")
s1 = " ".join(s.split()[::-1])
lists = s1.split()
for i in lists:
    if i.istitle() == True:
        print i

它目前的作用是反转一个字符串,如果以大写字母开头则打印一个单词。但问题是,如果一个单词就像“CApital”,它就不会打印出来。

让我举一些例子说明我希望该程序如何运作:

  1. 按相反顺序阅读
  2. 只关注消息中以单词开头的单词 大写字母

    如果这是输入的话:BaSe fOO ThE AttAcK 然后它应该返回:攻击基地

  3. 另一个例子:

    code: soMe SuPPLies liKE Ice-cREAm aRe iMPORtant oNly tO THeir cReaTORS. tO DestroY thEm iS pOInTLess.
    says: destroy their ice-cream supplies
    

    非常感谢你!

4 个答案:

答案 0 :(得分:3)

您不需要istitle

if word[0].isupper():
    # do stuff

答案 1 :(得分:1)

.istitle()仅在每个单词的首字母大写时才为真:

print 'MArk'.istitle()
print 'Mark'.istitle()  # True
print 'MARK'.istitle()
print 'marK'.istitle()
print 'Spam SPAM'.istitle()
print 'SPam Spam'.istitle()
print 'Spam Spam'.istitle() # True

所以只需测试第一个字母:

strings = [
    'BaSe fOO ThE AttAcK',
    'soMe SuPPLies liKE Ice-cREAm aRe iMPORtant oNly tO THeir cReaTORS. tO DestroY thEm iS pOInTLess']
for s in strings:
    print ' '.join(
        i for i in reversed(s.split()) if i[0].isupper()
        ).lower()

输出:

attack the base
destroy their ice-cream supplies

答案 2 :(得分:0)

for i in lists:
    if i[0].isupper() and  i[1].islower():
        print i

答案 3 :(得分:0)

你可以试试这个

s1 = s.split()[::-1]
for word in s1:
    if word[0].istitle() is True:
        out_list.append(word.lower())
print " ".join(out_list)

或更复杂但更短的版本

print " ".join(map(str.lower, filter(lambda x:x[0].istitle(), s.split()[::-1])))