python - Join author names with first ones separated by comma and last one by "and" -
i'm new python , have list of names separated \and
, need join separating first ones comma , last 1 'and'. if there more 4 names return value should first name along phrase 'et al.'. if have
authors = 'john bar \and tom foo \and sam foobar \and ron barfoo'
i should 'john bar et al.'. whereas with
authors = 'john bar \and tom foo \and sam foobar'
i should 'john bar, tom foo , sam foobar'.
it should work 1 author name, returning single name (and surname) itself.
i tried doing like
names = authors.split('\and') result = ', '.join(names[:-1]) + ' , '.join(names[-1])
but doesn't work. question how can use join
, split
first authors separated comma , last 'and' taking account if there more 4 authors first author name should returned along 'et al.'.
start splitting out names:
names = [name.strip() name in authors.split(r'\and')] # assuming raw \ here, not escape code \a.
then rejoin based on length:
if len(names) >= 4: authors = '{} et al.'.format(names[0]) elif len(names) > 1: authors = '{} , {}'.format(', '.join(names[:-1]), names[-1]) else: authors = names[0]
this works entries one author too; reassign name authors
.
combined function:
def reformat_authors(authors): names = [name.strip() name in authors.split(r'\and')] if len(names) >= 4: return '{} et al.'.format(names[0]) if len(names) > 1: return '{} , {}'.format(', '.join(names[:-1]), names[-1]) return names[0]
with demo:
>>> reformat_authors(r'john bar \and tom foo \and sam foobar \and ron barfoo') 'john bar et al.' >>> reformat_authors(r'john bar \and tom foo \and sam foobar') 'john bar, tom foo , sam foobar' >>> reformat_authors(r'john bar \and tom foo') 'john bar , tom foo' >>> reformat_authors(r'john bar') 'john bar'
Comments
Post a Comment