Python Character Limiter
How can I limit a string based on character count, and in the same time preserve complete words ?
I just don't want to slice, but even want to pr开发者_Go百科eserve the complete words. Please guide me ..
Edit
Example
string = "stackoverflow rocks , I know it."
so I need a function, for example
limiter(string,5)
which should return a complete word (stackoverflow
in this example), even if the limit I have set is 5. Thus preserving the meaning of words..
limiter(string,25)
desired result
stackoverflow rocks , I know
Thanks !
Will this work for you?
#!/usr/bin/python
def limiter(x, limit):
for i in range(len(x)):
if i >= limit and x[i] == " ":
break
return x[:i]
def main():
x = "stackoverflow rocks , I know it."
print limiter(x, 5)
print limiter(x, 25)
if __name__ == '__main__':
main()
If what you want to do is word-wrapping a string then a simple approach is the following:
- Begin looking at character
start + max_width
- Go backward one character at a time until you find a word breaking char
- If you found one then split there, if you reached instead
start
then nothing can be done and just print out the whole line
精彩评论