开发者

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:

  1. Begin looking at character start + max_width
  2. Go backward one character at a time until you find a word breaking char
  3. If you found one then split there, if you reached instead start then nothing can be done and just print out the whole line
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜