DEV Community

Cover image for Format a list for a title in Python
Victor Edier
Victor Edier

Posted on

Format a list for a title in Python

Some times is need it to show a list of items, but are you tire of the simple lists joined comma?
Alt Text
No?! Well I do, and this is the reason for this code snippet than can change your life ... well maybe not, but I found useful.

Given a list of strings X,Y,Z it will return a simple string separated by comma but the last element will be separated by the string ' and ', thats it.

def formatListforTitle(words):
  """
  This function returns a string like:
  For W,X,Y,Z
    W, X, Y and Z
  For X,Y
    X and Z
  """
  words = [s for s in words if s]
  if not words:
    return ''
  if len(words) == 1:
    listTitle = words[0]
  else:
    listTitle = ', '.join(words[:len(words) - 1]) + ' and ' + words[-1]
  return listTitle
Enter fullscreen mode Exit fullscreen mode

This is my first post, I hope all you people like it.

Top comments (0)