Search code examples
pythonpython-3.xvariablessplit

From printing a list how can I remove brackets, quotes and insert "and" before each last name


This code gives me the output: The names found are: ['Alba', 'Dawson', 'Oliver']

I would need to remove the brackets and quotes, and always print "and" before the last name (the number of names can be variable and for example I could have 3,4,5,6 names), so I would need this output:

The names found are: Alba, Dawson and Oliver

Code

name = "Alba, Dawson, Oliver"

names = name.split(', ')

print("The names found are: ", names)

How can I achieve this?


Solution

  • Once you've split the list into individual names, you can rejoin it with , or and dependent on the length of the list:

    name = "Alba, Dawson, Oliver"
    names = name.split(', ')
    print("The names found are: ", end = '')
    if len(names) == 1:
        print(names[0])
    else:
        print(', '.join(names[:len(names)-1]), 'and', names[-1])
    

    Output:

    The names found are: Alba, Dawson and Oliver