检查字符串中的最后一个空格?

时间:2017-11-16 21:56:38

标签: python

我有一个字符串"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

3 个答案:

答案 0 :(得分:2)

由于知道在哪里打破你的行取决于一个单词的长度,你不能通过将T视为一系列字符来做到这一点,除非你想要回溯(如果你半途而废,没有空间吗?)。

我会将T分成一个单词列表,然后运行它们:

lines = []
line = ''

for word in T.split(' '):
    if len(word) + len(line) <= L:
        # we can add the word onto the end of the current line
    else:
        # the word flows past the end of the current line, start a new one

请注意,您的预期输出不会在第30列上换行,它会在第25列换行。否则,第3行将包含26个字符并包含:

prosuere, risus non mollis

另一种解决方案是使用str.rfind的限制参数找到断点,然后使用它迭代地分解text

while T:
    # If T is already short, we don't have to worry about breaking it up
    if len(T) <= L:
        line = T
        T = ''
    else:
        # Find the rightmost space in the T that occurs before column L
        furthest_space = T.rindex(' ', 0, L)

        # Now you can figure out the next line from the position of the
        # furthest space and cut that part off of your T
        ...

    print(line)

答案 1 :(得分:1)

我认为最好的方法是将句子分成一个列表并用它来计算字符数。我不知道我是否理解s变量。我在每行的每个最后一个单词之后存储了空格。

T = "Quisque pretium magna ac aliquet interdum. Mauris posuere, risus non mollis placerat, diam ligula commodo justo, ac aliquet velit ante a ipsum."
L = 30

listofwords = T.split()

totalchars = 0
sentence = []
s=[]
for word in listofwords:
    if totalchars+len(word)+1 < L:
        totalchars+=len(word)+1
        sentence.append(word)
    elif totalchars+len(word)+1 ==L:
        totalchars+=len(word)+1
        sentence.append(word)
        print(' '.join(sentence))
        sentence = [word]
        totalchars = len(word)
    elif totalchars+len(word)+1 > L:
        s.append(totalchars+1)
        print(' '.join(sentence))
        sentence = [word]
        totalchars = len(word)
print(' '.join(sentence))
print(s)

答案 2 :(得分:0)

我的示例可能需要在异常或奇怪的输入值的情况下加强,但我认为您可以通过以下步骤来完成此操作:

  1. 以30个字符剪掉字符串
  2. 如果需要,将字符串拆分为最后一个空格。
  3. 也许是这样的:

    input = "Quisque pretium magna ac aliquet interdum. Mauris posuere, risus non mollis placerat, diam ligula commodo justo, ac aliquet velit ante a ipsum."
    final_string = ''
    cut_length = 30
    while input:
        temp = input[:cut_length]
        if input[cut_length] != ' ':
            temp = temp.split(" ", 1)[0]
        final_str += temp + "\n"
        input = input.replace(temp, '', 1)
    print(final_str)