0

I want to find the last white space of the string, and them break it there. line_size is the size that the line has to be, so it varies.

if line[line_size] != ' ':
        for x in reversed(range(line_size)):
            print line[x]
            if line [x] == ' ':
            break_line = line[x]

3 Answers 3

6

you should use rfind for the same

In [71]: l = "hi there what do you want"

In [72]: l.rfind(' ')
Out[72]: 20

rfind Return the highest index in the string where substring sub is found

the problem in your case seems to be with line_size you can go for reversed(range(len(l)))

In [76]: for x in reversed(range(len(l))):
   ....:     if l[x] == ' ':
   ....:         print x
   ....:         break
   ....:
20
Sign up to request clarification or add additional context in comments.

Comments

0

Indices in Python are zero-based, so if line_size = len(line) (the number of characters in line), then the last character of line is line[line_size-1].

1 Comment

Ah, first statement, I see it now. :-)
0

Assuming line_size = len(line), this will always fail

if line[line_size] != ' ':

because the first item is line[0], the last item is line[len(line)-1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.