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?
CodePudding user response:
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
CodePudding user response:
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])