0

Given the following strings as input to a Pythonic method:

The Adventures of Sherlock Holmes

The Art of War

A Tale of Two Cities

A Princess of Mars

I would like to see the following as the output:

Adventures of Sherlock Holmes, The

Art of War, The

Tale of Two Cities, A

Princess of Mars, A

Any ideas please?

4

1 回答 1

2

首先,split关闭第一个词:

first, rest = title.split(None, 1)

现在,检查第一个单词是否是文章:

if first in {'A', 'An', 'The'}:

如果是这样,请将其移至末尾:

    return rest + ', ' + first

把它们放在一起:

def fix_title(title):
    first, rest = title.split(None, 1)
    if first in {'A', 'An', 'The'}:
        return rest + ', ' + first
    return title

如果您希望能够正确处理空行,则需要更多逻辑,我认为在这种情况下,使用partition而不是split. 只需将中间的两行更改为:

    first, _, rest = title.partition(' ')
    if first in {'A', 'An', 'The'} and rest:
于 2013-10-09T22:24:31.887 回答