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 |