Text Wrap

  • + 0 comments

    HAVE PATIENCE, YOU'LL UNDERSTAND IT EASILY.

    **import textwrap

    def wrap(string, max_width): wrapper = textwrap.TextWrapper(width=max_width) result = wrapper.fill(text = string) if max_width <= len(string): return result else: print("Invalid width given")

         if __name__ == '__main__':
             string, max_width = input(), int(input())
                 result = wrap(string, max_width)
                 print(result)
    

    the above mentioned is the code, and below is the explaination

    FUNCTIONS USED

    1. textwrap.TextWrapper(width=max_width):

      • Creates a TextWrapper object that wraps text to the specified max_width.
    2. wrapper.fill(text=string):

      • Wraps the string into lines of max_width and returns a single string with line breaks.

    ((wrapper.wrap) stores it as a list while (wrapper.fill) stores it as a string)

    1. len(string):

      • Returns the length of the string.
    2. input():

      • Reads a line of input from the user.

    FLOW

    1. Input: The user inputs a string and a maximum width (max_width).

    2. Wrapper Setup: A TextWrapper object is created with the specified width.

    3. Text Wrapping: The fill() method wraps the input string into lines that fit the max_width, returning a single string with embedded line breaks.

    4. Condition Check: The code checks if max_width is less than or equal to the length of the string:

      • If true, the wrapped string is returned.
      • If false, "Invalid width given" is printed.
    5. Output: The result (either the wrapped string or the error message) is printed.

    if name == 'main': string, max_width = input(), int(input()) result = wrap(string, max_width) print(result)**