简体   繁体   中英

Replacing a space with a new line in a long string in order to "wrap a text"

I need to use a long string as a label in seaborn graph. If I use the long string the effective plot area is reduced so I want to wrap the lines, see below:

在此处输入图像描述

What I want to do is take a long string eg:

'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'

and every n characters (eg 30) find a space and replace it with a newline character "\n". So I get

'Lorem ipsum dolor sit amet, consectetur\nadipiscing elit, sed do eiusmod\ntempor incididunt ut labore et\ndolore magna aliqua.'`

I've managed to create a recursive function

def string_for_plot(raw_str:str, n:int = 30):
    a_indx = raw_str.find(' ',n)
    if a_indx>0:           
        return raw_str[:a_indx]+'\n' + string_for_plot (raw_str[a_indx+1:], n=n)            
    elif a_indx == -1:
       return raw_str

This works just fine, but I was wondering if I can use a more efficient method/more pythonic way to do this (eg regular expressions, some other string function that I am not aware of).

My own approach would be the following:

Iterate over the words and as long as the word fits into the line (the maximum length is not exceeded), add the word to the line.

But if the line would be to long, add the word to the next line.

Note that the first word in the first line is preceded with a whitespace (because we add every time a space and then the word to the line), so we have to return the lines but not the first character.

full code:

def split(input_line, max_length):
    lines = []
    cur_line = ""
    for word in input_line.split():
        if len(cur_line) + len(word) > max_length:
            lines.append(cur_line)
            cur_line = word
        else:
            cur_line += " " + word
    return "\n".join(lines)[1:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM