【发布时间】:2018-10-17 18:00:24
【问题描述】:
我正在尝试在控制台中输出一个字符串,以便以固定的行长度切断该字符串并在新行上继续该字符串 - 使该字符串具有报纸文章的外观。
这个,我做到了。 但是,我希望实现一个系统,使单词不会在中间被切断,打乱阅读的流程。我希望在行尾插入一个连字符。
这是我目前的输出:
这是我想要的输出:
我尝试在第 9 行更改我的代码,使其如下所示,但这导致连字符被放置在每一行的末尾——这不是我想要的。
if(outStr[i+1] == " "):
如何更改我的代码以创建我想要的输出?此函数必须能够处理任何长字符串,因为它将作为更大程序的一部分多次使用。
这是我用 Python 3.6.5 编写的代码:
lorumIpsum = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source."
def OutputStringToBook(outStr):
# Take each character
for i in range(len(outStr)):
# If the character is at the designated line end
if (i % 30 == 0):
# If the next character is not a space
if(outStr[i+1] != " "):
print()
else:
print("-")
print(outStr[i], end="")
else:
print(outStr[i], end="")
#time.sleep(0.01)
OutputStringToBook(lorumIpsum)
【问题讨论】:
-
range(len(outStr))在 Python 中是一个很大的禁忌(大部分情况下)。请改用for ind, i in enumerate(outStr) -
@Agile_Eagle:该链接不适用。 OP 能够很好地分配字符串;问题是自动换行。
标签: python string python-3.x output