首页 > 解决方案 > 在用户输入的某些点处切片和添加换行符的正确方法

问题描述

我有一个正在进行的程序,其中一个功能是获取一个可能很长的用户提供的字符串。但是,我需要确保字符串在某些点断开。我希望每行不超过 50 个字符,但必须在空格处中断。

对我来说似乎有意义的事情是运行一个 if 函数来测试字符串的长度,将其切成 50 个字符的长度,找到最后一个空格,然后在该点插入一个换行符。对我来说,这让代码看起来很笨拙。有没有更流畅、更 Pythonic 的方式来做到这一点?

instr = input()
if len(instr) > 50:
    n = instr[:50].rfind(' ')
    instr.replace(instr[n], "\n")
    n += 50
    if len(instr) > n:
        n = instr[:n].rfind(' ')
        instr.replace(instr[n], "\n")
        n += 50

如您所见,该循环可能会一直持续下去,尽管如果它超过一定长度,我会让它生成一条错误消息。这段代码可以满足我的要求,但是有更好的方法吗?

标签: pythonstringslice

解决方案


我参加聚会有点晚了,但这里有一个解释过的自动换行脚本,演示了如何编写一个。

我把最后几句话结合起来做了一个很长的词来展示它处理这个问题。

希望你觉得这个有用 :)

string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,suntinculpaquiofficiadeseruntmollitanimidestlaborum."
length = 50

# split text into words
words = string.split(" ")

new = ""
for word in words:

    # Calculate length of current line
    current_length = len(new.split("\n")[-1])

    if len(word) <= length:
        if current_length + len(" ") + len(word) > length:
            # If the new word would take the line's length over the maximum

            # Add a new line and the word
            new += "\n" + word
        else:
            if current_length != 0:
                # to avoid adding a space at the start of the wrapped setence

                # Add a space between words
                new += " "
            new += word # Add the word on to the end
    else:
        # if the length of the word is already longer than the maximum

        # Break words into lines no more than (the maximum length - 1) chunks, and add a hyphen at the end
        new_word = '\n'.join([word[i:i+length-1] + "-" for i in range(0,len(word),length-1)])

        # Remove the final hyphen from the end
        new_word = new_word[:-1]

        # Add it onto the end
        new += '\n' + new_word

print(new)

输出:

Lorem ipsum dolor sit amet, consectetur adipiscing
elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non
proident,suntinculpaquiofficiadeseruntmollitanimi-
destlaborum.

推荐阅读