Text Wrap in Python

I was working on a problem at HackerRank. It’s called text wrap problem. I was able to solve it with the following code.

def wrap(string, max_width):
    result = ''
    lines = len(string) / max_width
    last_chars = len(string) % max_width
    for i in range(int(lines)):
        start_index = i * max_width
        result += string[start_index:start_index+max_width] + '\n'

    if last_chars > 0:
        result += string[-last_chars:]
    return result

Then, I headed to Discussions section to see if a smarter person posted a better and more concise code. There was one.

def wrap(string, max_width):
    return "\n".join([string[i:i+max_width] for i in range(0, len(string), max_width)])

In essence, it’s pretty much the same logic but it’s more concise though I think it’s kind of harder to read. One of the important things we have to consider when coding is whether the code is maintainable and readable. But there are smarter people out there… Always learning.

Leave a Reply

Your email address will not be published.