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

2024-09-29 06:22:15 发布

您现在位置: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

Tags: 字符串inregacnonmagnarisusplacerat
3条回答

我认为最好的方法是把句子分成一个列表,用它来计算字符数。我不知道我是否正确理解了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)

我的示例可能需要在出现异常或奇怪的输入值时进行加固,但我认为您可以通过以下步骤来完成这一点:

  1. 把字符串删去30个字符
  2. 如果需要,在最后一个空格上拆分字符串。你知道吗

可能是这样的:

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)

因为知道在哪里换行取决于一个单词的长度,所以你不能把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)

相关问题 更多 >