1

I am trying to write a function that takes a user inputted list, and transforms it into a string that separates each value inside the list with a comma, and the last value in the list with "and". For example, the list ['cats', 'dogs', 'rabbits', 'bats'] would be transformed to: 'cats, dogs, rabbits, and bats'. My code works if I assign a list to a variable and then pass the variable to my newString function, but if I pass a user input to my function, it will treat every character in the user input as a separate list value.

So my question is, how can I tell Python that I want input() to be read as a list. Is this even possible? I am very new to Python and programming in general, so Lists and Tuples is about as far as I know so far. I am learning dictionaries now. My code is printed below, thanks.

def listToString(aList):

    newString = ''
    for i in range(len(aList) - 1):
        newString += aList[i] + ', '


    newString = newString + 'and ' + aList[-1]

    return(newString)



spam = list(input())

print(listToString(spam))
roganjosh
  • 12,594
  • 4
  • 29
  • 46
  • This is related to numbers, but it's basically the same idea. http://stackoverflow.com/questions/4663306/get-a-list-of-numbers-as-input-from-the-user – akousmata Jan 30 '17 at 20:51

3 Answers3

0

input() always gives you just a string.

You can analyze that string depending on how the user is supposed to enter the list.

For example, the user can enter it space separated like 'cats dogs rabbits bats'. Then you do

input_list = input().split()
print(listToString(input_list))

You can also split on , or any delimiter you like.

Hannes
  • 1,118
  • 8
  • 15
  • Your statement *"input() always gives you just a string"* is true only in case of Python 3. In Python 2, it returns the type of object (based on `eval` value) – Moinuddin Quadri Jan 30 '17 at 18:49
  • @MoinuddinQuadri Good point! :) But Python 3 is the only Python I use, everybody else without legacy dependencies should use, newcomers should learn *and* which is tagged in the question. – Hannes Jan 30 '17 at 18:52
0

If you want to read a list literal from user input, use ast.literal_eval to parse it:

import ast

input_list = ast.literal_eval(input()) # or ast.literal_eval(raw_input()) on Python 2
user2357112
  • 260,549
  • 28
  • 431
  • 505
0

You could build a list from the input and use your current working code to format it as you want.

def get_user_input():
    my_list = []
    print('Please input one word for line, leave an empty line to finish.')
    while True:
        word = input().strip()
        if word:
            my_list.append(word)
        else:
            break
    return my_list
Dalvenjia
  • 1,953
  • 1
  • 12
  • 16