Skip to content

Instantly share code, notes, and snippets.

@codebynumbers
Last active January 3, 2016 07:59
Show Gist options
  • Select an option

  • Save codebynumbers/8433534 to your computer and use it in GitHub Desktop.

Select an option

Save codebynumbers/8433534 to your computer and use it in GitHub Desktop.
def limit(s, max):
""" Limit string s to x characters respecting space boundaries
>>> limit('cat dog', 3);
'cat'
>>> limit('cat', 3);
'cat'
>>> limit('cat ', 4);
'cat'
>>> limit('cat dog', 5);
'cat'
>>> limit('cat dog bird', 10);
'cat dog'
>>> limit('cat', 9);
'cat'
"""
if len(s) <= max:
return s
for i in range(max-1, 0, -1):
if s[i] == ' ':
max = i
break
# max b/c slice is exclusive at the end
return s[:max]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment