string = "hello world i'm a new program"
words_length = []
length = 21
我re.split
用来产生单词和空格的列表:
words = re.split('\w', string)
所以:
words = ['hello', ' ', 'world', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program']
for x in words:
words_length.append(len(x))
for x in range(len(words)):
if words_length < length:
words_length += letters_length[x]
line += words[x]
del words[x]
但是最后,当我打印变量时,我得到了:
line = "helloworldi'manew"
words = [' ', ' ', ' ', ' ', ' ', 'program']
但是我想要的是:
line = "hello world i'm a new"
words = ['program']
我该如何做到这一点?
您正在跳过索引,因为要从列表中删除字符。
每次删除一个字符时,该字符右侧的所有内容都会向左向上移动一级,而其索引会向下移动一个。但是您的x
索引仍然上升一个,因此现在您引用列表中的后一个元素:
for循环的第一次迭代:
x == 0
words == ['hello', ' ', 'world', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program']
# 0 1 2 3 4 5 ...
words[x] == 'hello'
del words[x]
words == [' ', 'world', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program']
# 0 1 2 3 4 5 ...
循环的第二次迭代:
x == 1
words == [' ', 'world', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program']
# 0 1 2 3 4 5 ...
words[x] == 'world'
del words[x]
words == [' ', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program']
# 0 1 2 3 4 5 ...
循环的第三次迭代
x == 2
words == [' ', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program']
# 0 1 2 3 4 5 ...
words[x] == 'i'
del words[x]
words == [' ', ' ', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program']
# 0 1 2 3 4 5 ...
至少在循环之后,才从列表中删除条目;您无需在循环中将其删除:
line = []
current_length = 0
for i, word in enumerate(words):
current_length += len(word)
if current_length > length:
i -= 1
break
line.append(word)
# here i is the index of the last element of words actually used
words = words[i + 1:] # remove the elements that were used.
line = ''.join(line)
或者,您可以删除单词(从效率高的反向列表中删除),但是然后使用while
循环并测试累积的长度:
line = []
current_length = 0
reversed_words = words[::-1]
while reversed_words:
l = len(reversed_words[-1])
if current_length + l > length:
break
line.append(reversed_words.pop())
current_length += l
words = reversed_words[::-1]
line = ''.join(line)
但是,如果您尝试将行长换行应用于Python字符串,则可以避免使用textwrap
模块来重新发明该滚轮。它可以轻松地在最大长度内进行换行:
wrapped = textwrap.fill(string, length)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句