简体   繁体   中英

Python: String index out of range

I have had a look at a lot of previous questions put up, but still couldn't find anything that'll help me here. Here's a code I wrote to Reverse a sentence. I could have used split() function, but I tried to do without it anyways.

s='abcdef ghij klmn op qrst uv w xy z'
s=s[::-1]
print s
j=0
p=''
while(j<len(s)):
    a=''
    while(s[j]!=''):
        a=a+s[j]
        j+=1
    p.append(a[::-1])
    j+=1
print p

It gives me a string index out of range error in the while bracket. Why?

Thanks a lot for the help.

Because in the second while loop you're incrementing j without checking if you're at the end yet.

Also, s[j]!='' will always be true for strings. If you can use the index operator on a string it means that there are characters. Otherwise there are none.

For example:

s = ''
s[0]  # IndexError, there are no characters so there can be no index

s = 'x'
s[0]  # Will be x and s[1] will give the same error as above

A little simpler version of your code (not really Pythonic, would be nicer to use lists and use ' '.join() ):

s = 'abcdef ghij klmn op qrst uv w xy z'
print s

p = ''
i = 0
word = ''
while i < len(s):
    c = s[i]
    if c == ' ':
        if p:
            p = word + ' ' + p
        else:
            p = word

        word = ''
    else:
        word += c
    i += 1

print p

And the clean/simple Pythonic version with split:

s = 'abcdef ghij klmn op qrst uv w xy z'
print s
p = ' '.join(s.split()[::-1])
print p

Your issue is with this inner loop:

while(s[j]!=''):
    a=a+s[j]
    j+=1

This loop allows j to exceed the length of s , you probably want to add an additional condition here to prevent this (I also removed the unnecessary parentheses):

while j < len(s) and s[j] != '':
    a=a+s[j]
    j+=1

I think you want to do this: -

s='abcdef ghij klmn op qrst uv w xy z'
s=s[::-1]
print s
j=0
p=[]
while(j<len(s)):
    a=''
    while(j<len(s) and s[j]!=' '):
        a=a+s[j]
        j+=1
    p.append(a[::-1])
    j+=1
print ' '.join(p)
while(s[j]!=''):
        a=a+s[j]
        j+=1

Here's is the problem.. Your last character is z .. When it reaches there, your while condition is true.. And it tries increment j to next index.. Which is out of bound..

You can probably move this condition also to your outer while loop.. Because you need to check both the conditions at the same time... Both the conditions must be true in your case..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM