Python — add suffix if string slice truncated contents

A common design pattern: truncate a string to X chars if the string is long, and show a ‘…’ to indicate the string has been truncated.

What’s the shortest way to write this code?

http://stackoverflow.com/questions/2872512/python-truncate-a-long-string

x[:10] + (x[10:] and '...')

3 thoughts on “Python — add suffix if string slice truncated contents

  1. Your second colon is in the wrong place; the code needs to be:

    x[:10] + (x[10:] and ‘…’)

    x[10:] returns the text from index 10 on if it exists, else an empty string. It is that empty string that determines whether the “and” condition is satisfied.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s