-1

首先,这是我的代码:

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

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

让我展示一些我希望程序如何工作的示例:

  1. 以相反的顺序阅读单词
  2. 只注意邮件中以大写字母开头的单词

    如果输入:BaSe fOO The AttAcK 那么它应该返回:攻击基地

另一个例子:

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

太感谢了!

4

4 回答 4

3

你不需要istitle

if word[0].isupper():
    # do stuff
于 2012-09-08T04:04:55.503 回答
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
于 2012-09-08T04:18:43.350 回答
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])))
于 2012-09-08T04:04:08.220 回答
0
for i in lists:
    if i[0].isupper() and  i[1].islower():
        print i
于 2012-09-08T03:53:10.900 回答