![](/img/trans.png)
[英]replace new line with space only if it isn't followed by another new line (undo hard wrap in text)
[英]Replacing a space with a new line in a long string in order to "wrap a text"
我需要在 seaborn 圖中使用長字符串作為 label 。 如果我使用長字符串,有效的 plot 區域會減少,所以我想換行,見下文:
我想要做的是取一個長字符串,例如:
“Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。”
並且每n
字符(例如 30 個)找到一個空格並將其替換為換行符“\n”。 所以我得到
'Lorem ipsum dolor sit amet,consectetur\nadipiscing elit,sed do eiusmod\ntempor incididunt ut labore et\ndolore magna aliqua。'`
我設法創建了一個遞歸 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
這工作得很好,但我想知道我是否可以使用更有效的方法/更pythonic的方式來做到這一點(例如正則表達式,我不知道的其他一些字符串 function )。
我自己的方法如下:
遍歷單詞,只要單詞適合該行(不超過最大長度),就將該單詞添加到該行中。
但如果該行太長,請將單詞添加到下一行。
請注意,第一行中的第一個單詞前面有一個空格(因為我們每次都添加一個空格,然后將單詞添加到該行),因此我們必須返回行而不是第一個字符。
完整代碼:
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:]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.