It looks like you indented so_far = new too much. Try this:
if guess in word:
print("\nYes!", guess, "is in the word!")
# Create a new variable (so_far) to contain the guess
new = ""
i = 0
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new # unindented this
Answer from Rob Wouters on Stack OverflowI'm writing a program that needs to iterate through a string and print the first letter of every word. I have the program working but I can't submit it because of a "String index out of range" error.
An example of what needs to happen is this:
Please type in a sentence: Humpty Dumpty sat on a wall
Output:
H
D
s
o
a
w
Here's my code:
sent = input("Please type in a sentence: ")
index = 0
sent_length = len(sent)
space = " "
print(sent[index])
while index <= sent_length:
index += 1
if sent[index] == space:
print(sent[index + 1])I'm getting the correct output but it says I have a "string index out of range" error on line 8. I can't figure out what's wrong with it
It looks like you indented so_far = new too much. Try this:
if guess in word:
print("\nYes!", guess, "is in the word!")
# Create a new variable (so_far) to contain the guess
new = ""
i = 0
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new # unindented this
You are iterating over one string (word), but then using the index into that to look up a character in so_far. There is no guarantee that these two strings have the same length.
String Index out of range
Python: String index out of range - Stack Overflow
Erreur "string index out of range", besoin d'aide svp.
Python string index out of range
Videos
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