I am working on the practice projects in chapter 4 of Automate the boring stuff with Python
.
In the Comma Code 'practice projects'
, it asks you to write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item.
Is there a shorter way to write this code?
I have defined my function and used a for
loop with range(len(list))
to iterate over the index of the list.
then I named my list and added some items to it.
I finished by calling the list.
def carpenter(Powertools):
for i in range(len(Powertools)-1):
print(Powertools[i] + ',', end='')
ToolBox = ['hammer','chisel','wrench','measuring tape', 'screwdriver']
carpenter(ToolBox)
print(' and ' + ToolBox[-1])
The output gave me the list items I wanted, with and inserted by the last item.
But I was wondering, is there a shorter way to write this code?
You can use a list comprehension inside join
like this and append and
followed by last item.
', '.join(x for x in ToolBox[:-1]) + ' and ' + ToolBox[-1]
Putting this to function can be done like this,
def carpenter(power_tools):
return ', '.join(x for x in power_tools[:-1]) + ' and ' + power_tools[-1]
tool_box = ['hammer','chisel','wrench','measuring tape', 'screwdriver']
joined = carpenter(tool_box)
print(joined) # hammer, chisel, wrench, measuring tape and screwdriver
Note that I have changed the variable names following PEP-8.
Also, there is no need for comprehension, you can do something like this for the same result.
def carpenter(power_tools):
return ', '.join(power_tools[:-1]) + ' and ' + power_tools[-1]
tool_box = ['hammer','chisel','wrench','measuring tape', 'screwdriver']
joined = carpenter(tool_box)
print(joined) # hammer, chisel, wrench, measuring tape and screwdriver
Use join() to make comma separated list and slice list until second last element and use string .format() for for combining last element
def carpenter(Powertools):
finalresult=",".join(Powertools[:-1])
print('{} and {}'.format(finalresult,Powertools[-1]))
ToolBox = ['hammer','chisel','wrench','measuring tape', 'screwdriver']
carpenter(ToolBox)
Result:
hammer,chisel,wrench,measuring tape and screwdriver
This should work:
def carpenter(powertools):
return ','.join(powertools[:-1]) + ' and ' + powertools[-1]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.