Created
July 27, 2018 20:07
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
hadrocodium
commented
Mar 27, 2022
def comma_code(words): if len(words) == 1: return words[0] return '{}, and {}'.format(', '.join(words[:-1]), words[-1])
# 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)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment