PYTHON IndexError : string index out of range - python

Problem statement : Write a function called censor that takes two strings, text and word, as input. It should return the text with the word you chose replaced with asterisks
Here is my code,
def censor(text, word):
i = 0
j = 0
ans = ""
while i<len(text):
while text[j] == word[j]:
j = j + 1
if text[j+1] == " " or j+1 == len(text):
while i<j:
ans += "*"
i = i + 1
ans += " "
i = i + 1
else:
while text[j] != " ":
j = j + 1
while i<=j:
ans += text[i]
i = i + 1
i = i + 1
j = j + 1
return ans
print censor("how are you? you are not fine.","you")
But I am getting the following error,
Traceback (most recent call last):
File "python", line 27, in <module>
File "python", line 7, in censor
IndexError: string index out of range

This is much more complicated than it needs to be. You can just do this:
def censor(text, censored_word):
return text.replace(censored_word, '*'*len(censored_word))
>>> censor('How are you? Are you okay?', 'you')
'How are ***? Are *** okay?'
If you don't want the word youth to be censored but you do want you to be censored, here's how:
def censor(text, censored_word):
repl = '*'*len(censored_word)
return ' '.join([repl if word == censored_word else word for word in text.split()])
If you want to have multiple censored words:
def censor(text, censored_words):
return ' '.join(['*'*len(word) if word in censored_words else word for word in text.split()])
When dealing with index errors, it is often helpful to print out the index and figure out why the index has a value not within the required bounds.

It's good to use string replace in python for replacing the string.
In your case, you should make use of word's length to match word in the text as:
def censor(text, word):
i = 0
j = 0
ans = ""
wl=len(word)
while i<(len(text)):
if word==text[i:i+wl]:
ans=ans+'*'*wl
i=i+wl
else:
ans=ans+text[i]
i = i + 1
return ans
print censor("how are you? you are not fine.","you")

Related

Python reverse each word in a sentence without inbuilt function python while preserve order

Not allowed to use "Split(),Reverse(),Join() or regexes" or any other
helping inbuilt python function
input something like this:
" my name is scheven "
output like this:
"ym eman si nevehcs"
you need to consider removing the starting,inbetween,ending spaces aswell in the input
I have tried 2 tries, both failed i will share my try to solve this and maby an idea to improve it
First try:
def reverseString(someString):
#lenOfString = len(someString)-1
emptyList = []
for i in range(len(someString)):
emptyList.append(someString[i])
lenOfString = len(emptyList)-1
counter = 0
while counter < lenOfString:
if emptyList[counter] == " ":
counter+=1
if emptyList[lenOfString] == " ":
lenOfString-=1
else:
swappedChar = emptyList[counter]
emptyList[counter] = emptyList[lenOfString]
emptyList[lenOfString] = swappedChar
counter+=1
lenOfString-=1
str_contactantion = ""
#emptyList = emptyList[::-1]
#count_spaces_after_letter=0
for letter in emptyList:
if letter != " ":
str_contactantion+=letter
#str_contactantion+=" "
str_contactantion+=" "
return str_contactantion
second try:
def reverse(array, i, j):
emptyList = []
if (j == i ):
return ""
for k in range(i,j):
emptyList.append(array[k])
start = 0
end = len(emptyList) -1
if start > end: # ensure i <= j
start, end =end, start
while start < end:
emptyList[start], emptyList[end] = emptyList[end], emptyList[start]
start += 1
end -= 1
strconcat=""
for selement in emptyList:
strconcat+=selement
return strconcat
def reverseStr(someStr):
start=0
end=0
help=0
strconcat = ""
empty_list = []
for i in range(len(someStr)):
if(someStr[i] == " "):
continue
else:
start = i
j = start
while someStr[j] != " ":
j+=1
end = j
#if(reverse(someStr,start,end) != ""):
empty_list.append(reverse(someStr,start,end))
empty_list.append(" ")
for selement in empty_list:
strconcat += selement
i = end + 1
return strconcat
print(reverseStr(" my name is scheven "))
The following works without managing indices:
def reverseString(someString):
result = crnt = ""
for c in someString:
if c != " ":
crnt = c + crnt # build the reversed current token
elif crnt: # you only want to do anything for the first space of many
if result:
result += " " # append a space first
result += crnt # append the current token
crnt = "" # and reset it
if crnt:
result += " " + crnt
return result
reverseString(" my name is scheven ")
# 'ym eman si nevehcs'
Try this:
def reverseString(someString):
result = ""
word = ""
for i in (someString + " "):
if i == " ":
if word:
result = result + (result and " ") + word
word = ""
else:
word = i + word
return result
You can then call it like this:
reverseString(" my name is scheven ")
# Output: 'ym eman si nevehcs'
Try this:
string = " my name is scheven "
def reverseString(someString):
result = ''
curr_word = ''
for i in someString:
if i == ' ':
if curr_word:
if result:
result = f'{result} {curr_word}'
else:
result = f'{result}{curr_word}'
curr_word = ''
else:
curr_word = f'{i}{curr_word}'
return result
print(repr(reverseString(string)))
Output:
'ym eman si nevehcs'
Note: if you're allowed to use list.append method, I'd suggest using a collections.deque as it's more performant than appending to a list. But of course, in the end you'll need to join the list together, and you mentioned that you're not allowed to use str.join, so that certainly poses an issue.

find function does not display desired string

Hey so I am doing a project that is supposed to be a word search calculator. The word search is a 10x10 list of characters turned into rows of characters. I did a .find function for my check forward, however it is not working correctly. I will provide my get puzzle function, my check forward and what the output should be (ignore the format of the puzzle for output).
def input_puzzle():
print("Puzzle:\n")
puzzle_input = input()
puzzle_list = []
for i in range(10):
row = ""
for j in range(10):
row += puzzle_input[i*10 + j]
puzzle_list.append(row)
return puzzle_list
def check_forward(puzzle_list, word, direction):
for row in range(len(puzzle_list)):
row_string = puzzle_list[row]
finder = row_string.find(word)
if finder > 0:
print(word + ":" + direction + "row:" + row, "column:", finder) # finder is the indeci in row #+ means right after and comma means space
return True
else:
print(word + ": word not found")
return False
"""
Puzzle:
WAQHGTTWEE
CBMIVQQELS
APXWKWIIIL
LDELFXPIPV
PONDTMVAMN
OEDSOYQGOB
LGQCKGMMCT
YCSLOAPUZM
XVDMGSXCYZ
UUIUNIXFNU
UNIX: (FORWARD) row: 9 column: 3
"""
The following code works
def input_puzzle():
print("Puzzle:\n")
puzzle_input = input()
puzzle_input = puzzle_input.strip()
puzzle_list = []
for i in range(10):
row = ""
for j in range(10):
row += puzzle_input[i*11 + j]
puzzle_list.append(row)
return puzzle_list
def check_forward(puzzle_list, word, direction):
for row in range(len(puzzle_list)):
row_string = puzzle_list[row]
finder = row_string.find(word)
if finder > 0:
print("{}: ({}) row: {} column: {}".format(word, direction, str(row), str(finder)))
return True
else:
continue
print(word + ": word not found")
print(check_forward(input_puzzle(), 'UNIX', 'FORWARD'))
# UNIX: (FORWARD) row: 9 column: 3

printing out or returning strings between brackets

I'm trying to write a function in similar manner as started, so that I will get what it's doing. I'm assuming this can be done with one line of code, with some fancy functions, but for the sake of practice and understanding I'm trying to come up with similar solution.
The task is the following: the function takes a text once it encounters enclosed square brackets [ word ] It should print out or return all words which are between square brackets. For example, if the text string would be "[a]n example[ string]", you are expected to print out "a string".
def string():
text = "some random text [and I need this bit of txt] but I don't know how to continue [to get this bit as well]"
for i in text:
for j in range(len(text)):
if text[j] == '[':
new = text.find(']')
return(text[j+1:new])
print(string())
Try this:
def extract(text, skip_chars=("\n", )):
output = ""
flag = False
for c in text:
if c == "]":
flag = False
if flag and not c in skip_chars:
output += c
if c == "[":
flag = True
return output
print(extract("""[a]n example[
stri
ng]"""))
# -> "a string"
def string():
result = []
text = "some random text [and I need this bit of txt] but I don't know how to continue [to get this bit as well]"
for i in text:
if i == '[':
new = text.find(']')
result.append(text[text.index(i) + 1:new])
return " ".join(result)
print(string())
def parse(source):
i = source.index("[") # throw an exception
result = ""
while i < len(source):
if s[i] == "[":
i += 1
while i < len(source):
temp = ""
if source[i] == "]":
result += temp
break;
temp += source[i]
i += 1
i += 1
return result

How to write a variable by replacing the letter of an other variable by one place in Python?

I'm learning Python and I'm having trouble with this script.
I need to write this word by replacing all the other letter by one place.
def replace_word(word):
letter = list(word)
i = 0
final_letter = letter[0]
guess = ""
while i + 1 < len(word):
guess = letter[i + 1]
final_letter += guess
i += 1
print(final_letter)
replace_word("hhello")
My goal is to have in the variable final_letter == "hello".
If you change the line final_letter = letter[0] to final_letter = '' your code would exactly do what you want it to do
def replace_word(word):
letter = list(word)
i = 0
final_letter = ''
guess = ""
while i + 1 &lt len(word):
guess = letter[i + 1]
final_letter += guess
i += 1
print(final_letter)
That being said, you could achieve the same by doing something as simple as this
def replace_word(word):
print(word[1:])

Translating sentences into pig latin

SO i have this assignment to translate multiple words into pig latin. assume that the user will always input lowercase and only letters and spaces.
#----------------global variables
sentence = input("What do you want to translate into piglattin? ")
sentence = list(sentence)
sentence.insert(0, ' ')
length = len(sentence)
sentence.append(' ')
pigLattin = sentence
false = 0
true = 1
consonant = []
a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
j = 0
x = 0
y = 0
#----------------main functions
def testSpace(sentence, i):
if sentence[i] == ' ':
a = true
else:
a = false
return a
def testVowel(sentence, i):
if sentence[i] == 'a' or sentence[i] == 'e' or sentence[i] == 'i' or sentence[i] == 'o' or sentence[i] == 'u' or sentence[i] == 'y':
b = true
else:
b = false
return b
def testStartWord(sentence, i):
x = 0
if sentence[i].isalpha() and sentence[i-1] == ' ':
c = true
x = 1
if x == 1 and sentence[i] != 'a' and sentence[i] != 'e' and sentence[i] != 'i' and sentence[i] != 'o' and sentence[i] != 'u' and sentence[i] != 'y':
c = true
else:
c = false
return c
def testWordEnd(sentence, i):
if sentence[i].isalpha() and sentence[i+1] == ' ':
d = true
else:
d = false
return d
#----------------main loop
for i in range(1,length):
x = 0
space = testSpace(sentence, i)
vowel = testVowel(sentence, i)
word = testStartWord(sentence, i)
end = testWordEnd(sentence, i)
if vowel == false and space == false and word == true:
e = i
consonant.append(sentence[i])
pigLattin.pop(e)
f = f + 1
if end == true:
consonant.append('a')
consonant.append('y')
consLength = len(consonant)
for x in range(consLength):
y = i + j - f
pigLattin.insert(y,consonant[x])
j = j + 1
del consonant[:]
pigLength = len(pigLattin)
for b in range (pigLength):
print(pigLattin[b], end='')
this is what i have so far. it gets kinda messy when trying to remove items. im sort of stuck here and its not working.
OK i got it working now this is an updated version
sentence = input("Please enter a sentence: ")
vowels = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")
words = sentence.split()
count = 0
def find_vowel(word):
for i in range(len(word)):
if word[i] in vowels:
return i
return -1
for word in words:
vowel = find_vowel(word)
if(vowel == -1):
print(word, ' ', end='')
elif(vowel == 0):
print(word + "ay", ' ', end='')
else:
print(word[vowel:] + word[:vowel] + "ay", ' ', end='')
Instead of using testSpace eliminate the spaces by using sentence = sentence.split(). This will split all your words into strings in a list. Then iterate through the words in your list.
Instead of using testStartWord, use an if statement:
for word in sentence:
if word[0] in ["a","e","i","o","u"]:
word[:(len(word)-1)] = word[0]
#More Code...
At the end, where you print the output, use print sentence.join()
Here's an alternate version. I use a regular expression to find words in the input string, pass them to a callback function, and substitute them back into the original string. This allows me to preserve numbers, spacing and punctuation:
import re
import sys
# Python 2/3 compatibility shim
inp = input if sys.hexversion >= 0x3000000 else raw_input
VOWELS = set('aeiouyAEIOUY')
YS = set('yY')
def pig_word(word):
"""
Given a word, convert it to Pig Latin
"""
if hasattr(word, 'group'):
# pull the text out of a regex match object
word = word.group()
# find the first vowel and what it is
vowel, where = None, None
for i,ch in enumerate(word):
if ch in VOWELS:
vowel, where = ch, i
break
if vowel is None:
# No vowels found
return word
elif where == 0 and vowel not in YS:
# Starts with a vowel - end in 'way'
# (leading y is treated as a consonant)
return word + 'way'
else:
# Starts with consonants - move to end and follow with 'ay'
# check capitalization
uppercase = word.isupper() and len(word) > 1
titlecase = word[:1].isupper() and not uppercase
# rearrange word
word = word[where:] + word[:where] + 'ay'
# repair capitalization
if uppercase:
word = word.upper()
elif titlecase:
# don't use str.title() because it screws up words with apostrophes
word = word[:1].upper() + word[1:].lower()
return word
def pig_latin(s, reg=re.compile('[a-z\']+', re.IGNORECASE)):
"""
Translate a sentence into Pig Latin
"""
# find each word in the sentence, pass it to pig_word, and insert the result back into the string
return reg.sub(pig_word, s)
def main():
while True:
s = inp('Enter a sentence to translate (or Enter to quit): ')
if s.strip():
print(pig_latin(s))
print('')
else:
break
if __name__=="__main__":
main()
then
Enter a sentence to translate (or Enter to quit):
>>> Hey, this is really COOL! Let's try it 3 or 4 times...
Eyhay, isthay isway eallyray OOLCAY! Et'slay ytray itway 3 orway 4 imestay...

Categories