Question

I don't see this question anywhere in the database - if it's a duplicate, please let me know!

I'm trying to format a string to a certain length by word; I have a string of arbitrary length and I would simply like to add newlines in every n characters, separated by word so that the string is not split in the middle of a word.

str = "This is a string with length of some arbitrary number greater than 20"
count=0
tmp=""
for word in str.split():
   tmp += word + " "
   count += len(word + " ")
   if count > 20:
      tmp += "\n"
      count = 0
str = tmp
print str

I'm certain that there is an embarrassingly simple Pythonic way to do this, but I don't know what it is.

Suggestions?

Was it helpful?

Solution

Use the textwrap module. For your case textwrap.fill should have it:

>>> import textwrap
>>> s = "This is a string with length of some arbitrary number greater than 20"
>>> print textwrap.fill(s, 20)
This is a string
with length of some
arbitrary number
greater than 20

OTHER TIPS

This may not be the most straight forward way, it's not efficient, but it outlines the process that lies within the pythonic one liners:

def example_text_wrap_function(takes_a_string,by_split_character,line_length_int):
    str_list = takes_a_string.split(by_split_character)
    tot_line_length = 0
    line = ""
    line_list = []
    for word in str_list:
        # line_length_int - 1 to account for \n
        if len(line) < (line_length_int - 1):
            # check if first word
            if line is '':
                line = ''.join([line,word])
            # Check if last character is the split_character
            elif line[:-1] is by_split_character:
                line = ''.join([line,word])
            # else join by_split_character
            else:
                line = by_split_character.join([line,word])
        if len(line) >= (line_length_int - 1):
            # last word put len(line) over line_length_int start new line
            # split(by_split_character)
            # append line from range 0 to 2nd to last "[0:-2]" and \n
            # to line_list
            list_out = by_split_character.join(line.split(by_split_character)[0:-1]), '\n'
            str_out = by_split_character.join(list_out)
            line_list.append(str_out)
            # set line to last_word and continue
            last_word = line.split(by_split_character)[-1]
            line = last_word
        # append the last line if word is last
        if word in str_list[-1]:
            line_list.append(line)

    print(line_list)


    for line in line_list:
        print(len(line))
        print(repr(line))
    return ''.join(line_list)

# if the script is being run as the main script 'python file_with_this_code.py'
# the code below here will run. otherwise you could save this in a file_name.py
# and in a another script you could "import file_name" and as a module
# and do something like file_name.example_text_wrap_function(str,char,int)

if __name__ == '__main__':

    tmp_str = "This is a string with length of some arbitrary number greater than 20"
    results = example_text_wrap_function(tmp_str,' ',20)
    print(results)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top