Quantcast
Channel: Lecciones Prácticas
Viewing all articles
Browse latest Browse all 33

Python: truncate string to n words [SOLVED]

$
0
0

A friend of mine asked how to implement a python function to truncate a string to the first n words. Easy!

def truncate_string(mystring, numberofwords):
    return ' '.join(mystring.split()[:numberofwords])

An example of use:

>>> sample_string = "hello world this is a string"
>>> print truncate_string(sample_string,2)
hello world

Viewing all articles
Browse latest Browse all 33

Trending Articles