Skip to content

Instantly share code, notes, and snippets.

@byanuaria
Created July 27, 2018 20:07
Show Gist options
  • Save byanuaria/2fdc8bc56fbcf631b6e97df8787fef29 to your computer and use it in GitHub Desktop.
Save byanuaria/2fdc8bc56fbcf631b6e97df8787fef29 to your computer and use it in GitHub Desktop.
Automate the boring stuff pratice project: Comma Code. A function that takes a list value as an argument and returns a string with all the items seperated by a comma and a space, with 'and' inserted before the last item.
# lists to test
foo = ['apples', 'bananas', 'tofu', 'cats']
a = ['bat', 'rat', 'elephant', 'snake', 'hippo']
b = ['Ben', 'Ryan', 'Arthur', 'Dillon', 'Andre', 'Agnes', 'Aaron']
d = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
# comma code function
def commaCode(myList):
s = '' # creates an empty string vector
last = myList[len(myList) - 1] # gets the last value from the list
length = int(len(myList)) - 1 # gets the length of the list
newList = myList[0:length] # creates a new list without the last value from the list
for words in newList:
s += words + ', ' # putting the values from the list as a string seperated by commas
print(s + ' and ' + last) # prints the final string with the last value added to it
commaCode(foo)
commaCode(a)
commaCode(b)
commaCode(d)
@TuanNg915
Copy link

TuanNg915 commented Jun 9, 2022

def comma_code(words): if len(words) == 1: return words[0] return '{}, and {}'.format(', '.join(words[:-1]), words[-1])

@0eufc0smique
Copy link

0eufc0smique commented Jul 28, 2022

# lists to test
foo = ['apples', 'bananas', 'tofu', 'cats']
a = ['bat', 'rat', 'elephant', 'snake', 'hippo']
b = ['Ben', 'Ryan', 'Arthur', 'Dillon', 'Andre', 'Agnes', 'Aaron']
d = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 

# comma code function
def commaCode(myList):
    s = '' # creates an empty string vector
    last = myList[len(myList) - 1] # gets the last value from the list
    length = int(len(myList)) - 1 # gets the length of the list
    newList = myList[0:length] # creates a new list without the last value from the list
    for words in newList:
        s += words + ', ' # putting the values from the list as a string seperated by commas
    print(s + 'and ' + last) # prints the final string with the last value added to it
                             # removed the extra space in ' and ', now displays correctly

commaCode(foo)
commaCode(a)
commaCode(b)
commaCode(d)

@Pejero95
Copy link

Screenshot 2025-04-08 195454

@Pejero95
Copy link

Comma Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment