Currently working my way through this beginners book and have completed one of the practice projects \'Comma Code\' which asks the user to construct a program which:
This is what I did, IMO it is more intuitive...
spam = ['apples','bananas','tofu','cats']
def ipso(x):
print("'" , end="")
def run (x):
for i in range(len(x)):
print(x[i]+ "" , end=',')
run(x)
print("'")
ipso(spam)
I tried this, hope this is what you are looking for :-
spam= ['apples', 'bananas', 'tofu', 'cats']
def list_thing(list):
#creating a string then splitting it as list with two items, second being last word
new_string=', '.join(list).rsplit(',', 1)
#Using the same method used above to recreate string by replacing the separator.
new_string=' and'.join(new_string)
return new_string
print(list_thing(spam))
listA = [ 'apples', 'bananas', 'tofu' ]
def commaCode(listA):
s = ''
for items in listA:
if items == listA [0]:
s = listA[0]
elif items == listA[-1]:
s += ', and ' + items
else:
s += ', ' + items
return s
print(commaCode(listA))
As the function must work for all list values passed to it, including integers, therefore it should be able to return/print all values i.e. as str(). My fully working code looks like this:
spam = ['apples', 'bananas', 'tofu', 'cats', 2]
def commacode(words):
x = len(words)
if x == 1:
print(str(words[0]))
else:
for i in range(x - 1):
print((str(words[i]) + ','), end=' ')
print(('and ' + str(words[-1])))
commacode(spam)
Here's my solution. Once I found the join method and how it worked, the rest followed.
spam = ['apples', 'bananas', 'tofu', 'cats']
def commas(h):
s = ', '
print(s.join(spam[0:len(spam)-1]) + s + 'and ' + spam[len(spam)-1])
commas(spam)
I came up with this solution
#This is the list which needs to be converted to String
spam = ['apples', 'bananas', 'tofu', 'cats']
#This is the empty string in which we will append
s = ""
def list_to_string():
global spam,s
for x in range(len(spam)):
if s == "":
s += str(spam[x])
elif x == (len(spam)-1):
s += " and " + str(spam[x])
else:
s += ", " + str(spam[x])
return s
a = list_to_string()
print(a)