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

Question:

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?

Asked By: Santiago E. 98

||

Answers:

I see: you want to replace the final comma (' ) with and. This will do it.

splitted = [name.strip() for name in names.split(',')]
as_string = ', '.join(splitted[:-1]) + ' and ' + splitted[-1]

Previous Answer

It sounds like you need to create a list, not assign to individual variables, and then index the list to get the names as variables.

name = "Alba, Dawson, Oliver"

names = name.split(', ')

print(names[0])
print(names[1])
print(names[2])

# but you can do this instead:
for i in range(len(names)):
    print(names[i])
Answered By: philosofool

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
Answered By: Nick
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.