How does one truncate a string to 75 characters in Python?
var data="saddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsadddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" var info = (data.length > 75) ? data.substring[0,75] + ".." : data;
info = (data[:75] + "..") if len(data) > 75 else data
Even shorter :
info = data[:75] + (data[75:] and "..")
If you are using Python 3.4+, you can use
textwrap.shorten from the standard library:
Collapse and truncate the given text to fit in the given width.
First the whitespace in text is collapsed (all whitespace is replaced by single spaces). If the result fits in the width, it is returned. Otherwise, enough words are dropped from the end so that the remaining words plus the placeholder fit within width:
>>> textwrap.shorten("Hello world!", width=12) "Hello world!" >>> textwrap.shorten("Hello world!", width=11) "Hello [...]" >>> textwrap.shorten("Hello world", width=10, placeholder="...") "Hello..."
Become a master in Python by learning coding best practices and advanced programming concepts in Python 3.7. This book is written for Python developers who wish to go further in mastering Python. A...
Deep Learning for Coders with fastai and PyTorch: AI Applications Without a PhD. Deep learning is often seen as the exclusive domain of math PhDs and big tech companies. But as this how-to guide sh...
This book contains chapters authored by several leading experts in the field of cloud computing. The book is presented in a coordinated and integrated manner starting with the fundamentals and followe...
This encyclopedia will be an indispensable resource for our time as it reflects the fact that we are currently living in an expanding data-driven world. ...