在单词Python末尾20个字符后创建字符串中的换行符

2024-06-02 04:54:09 发布

您现在位置:Python中文网/ 问答频道 /正文

在这一点上,我尝试了多种方法,但无法解决自己的问题。 在字符串中第20个字符之前的任何点(越接近20越好),但必须在空格之后,我需要Python代码自动插入换行符

例如:

string = "A very long string which is definately more than 20 characters long"

我需要在字串(第19个字符)后的空格处插入“\n”,然后再在肯定(前一个换行符后的第20个字符)后插入

基本上,我需要一个句子跨越一个20个字符的屏幕,如果接近边缘,就在一个单词的结尾处中断

一个可能的概念可能包括在第15个字符后搜索空格,然后在那里中断?我不确定这将如何在那里实施

希望这是有意义的


Tags: 方法字符串代码whichstringismorelong
2条回答

也许有更好的方法可以做到这一点,但这似乎是可行的:-

s = "A very long string which is definately more than 20 characters long"
offset = 0
try:
    while True:
        p = s.rindex(' ', offset, offset + 20)
        s = s[:p] + '\n' + s[p + 1:]
        offset = p
except ValueError:
    pass

print(s)

此代码可以改进,但您可以从以下内容开始:

def until_x(string: str, x : int = 20) -> str:
     """
     params:
     string <str>: a str object that should have line breaks.
     x <int>: the max number of characters in between the line breaks.
     
     return:
     a string which has line breaks at each x characters.
     
     usage:
     >>> str_ = 'A very long string which is definately more than x characters long'
     >>> until_x(str_)  # default value of x is 20
     'A very long string \nwhich is definately \nmore than x \ncharacters long '
     >>>
     >>>until_x(str_, 30)
     'A very long string which is \ndefinately more than x \ncharacters long '
     >>>
     """
     lst = string.split()
     line = ''
     str_final = ''
     for word in lst:
         if len(line + ' ' + word) <= x:
             str_final += word + ' '
             line += word + ' '
         else:
             str_final += '\n' +  word + ' '
             line = word + ' '
     return str_final

相关问题 更多 >