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)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay