Inputting multiple strings and finding their length I need to find the length of elements within a string and return it to the user.

What is the best way of simplifying this code to make the amount of string lengths equate to user input? Also, how can I replace string1 with the user input, such as "The length of string 'Dog' is 3"?

num_of_items = int(input("How many items in your list? "))
def item_list(x):

    items = []
    for i in range(0, x):
        item = input("Enter list %r: " % (i+1))
        items.append(item)
        length_items = ''.join(items)

    return "Itemlist: %r" %(items), "Total length: %s"% len(length_items), \
    "The length of string 1 is %r"%len(items[0]),\
    "The length of string 2 is %r"%len(items[1]),\
    "The length of string 3 is %r"%len(items[2]),\
    "The length of string 4 is %r"%len(items[3])

print(item_list(num_of_items))
num_of_items = int(input("How many items in your list? "))



For one thing, what if the user typed alpha?  You would have a nasty error throwing itself at the user.  Why are you asking anyway?  You should be able to handle any number of items without asking.  Just keep asking input and printing output until the user decides to end with exit.  Even as it is, your item_list() function will print only the first four and if num_of_items is, say, three ... IndexError.


num_of_items ...
def item_list(x):
    ...



That's a little squooshed.  I would add at least one blank line and probably two between the num_of_items definition and the item_list() definition.  Well, actually I would put the num_of_items definition below the function definition.  Usually, constants are defined first; then functions and classes; then variables.


item = input("Enter list %r: " % (i+1))



% formatting is not officially deprecated, but it is preferred to use .format()

I wouldn't create a list of strings whose sole purpose is to be displayed to the user.  There are some things such as get_accuracy(user) where you might not use it elsewhere, but it makes sense to use it programmatically.  In this case, you are returning strings that couldn't be read by your program very easily.  Your item_list() function should not return strings that are formatted just for the reader.  It should return something that you can format however you like elsewhere.  My modified program looks like this:

def get_items():
    while True:
        item = input("Enter string: ")
        if item.lower() == "exit":
            raise StopIteration()
        yield item, len(item)

for item in get_items():
    print("The length of string '{0}' is {1}".format(*item))


get_items() is now a generator function that yields tuples of each item and its length.  Since it raises StopIteration when the user types exit, the for loop will stop.