Last active
January 3, 2016 07:59
-
-
Save codebynumbers/8433534 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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