我有一个字符串"Quisque pretium magna ac aliquet interdum. Mauris posuere, risus non mollis placerat, diam ligula commodo justo, ac aliquet velit ante a ipsum."
存储在变量T
中,还有一个变量L
设置为30
。你知道吗
我正在尝试编写一个循环来打印字符串,但是这种方式只能容纳L
个字符(本例中为30个字符)。如果有一个单词超过了限制(比如,它从字符28开始,到字符32结束),那么我试图将最后一个空格所在的索引(最近的" "
的索引)存储在一个名为s
的变量中。这就是我所拥有的,但我不知道从这里走到哪里:
finalstr = ""
reg = re.compile('[a-z]')
for i in range(0, L):
if T[i] >= L and reg.search(T[i]):
finalstr += "\n"
else:
finalstr += T[i]
return finalstr
我想要的是:
Quisque pretium magna ac
aliquet interdum. Mauris
prosuere, risus non
mollis placerat, diam
ligula commodo justo, ac
aliquet velit ante a
ipsum.
然而,这是我得到的回溯,我做错了什么?你知道吗
Traceback (most recent call last):
File "problem.py", line 146, in <module>
print wrap(T, L)
File "problem.py", line 122, in wrap
if T[i] >= L and reg.search(T[i]):
IndexError: list index out of range
我认为最好的方法是把句子分成一个列表,用它来计算字符数。我不知道我是否正确理解了
s
变量。我在每行的最后一个单词后都存储了空格。你知道吗我的示例可能需要在出现异常或奇怪的输入值时进行加固,但我认为您可以通过以下步骤来完成这一点:
可能是这样的:
因为知道在哪里换行取决于一个单词的长度,所以你不能把
T
当作一个字符序列来处理,除非你想回溯(如果一个单词读到一半,空间就用完了怎么办?)。你知道吗相反,我会将
T
分解成一个单词列表,然后遍历它们:请注意,预期的输出不会在第30列换行,而是在第25列换行。否则,第3行将为26个字符长,并包含:
另一种解决方案是,通过使用
str.rfind
的极限参数来找到断点,然后使用以下方法迭代分解text
:相关问题 更多 >
编程相关推荐