Vamsi Krishna B
Vamsi Krishna B

Reputation: 11490

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 preserve 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 !

Upvotes: 3

Views: 1901

Answers (2)

Rumple Stiltskin
Rumple Stiltskin

Reputation: 10385

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()

Upvotes: 5

6502
6502

Reputation: 114461

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

Upvotes: 4

Related Questions