Reputation: 600
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 e.g.:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
and every n
characters (e.g. 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 (e.g. regular expressions, some other string function that I am not aware of).
Upvotes: 0
Views: 703
Reputation: 1116
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:]
Upvotes: 1