I am asked the following:
def myRemove( str, ch ):
# Return a new string with the first occurrence of ch removed. If there is none, return str.
Sample run
>>> myRemove( "abcdabcd", "a")
'bcdabcd'
>>> myRemove( "abcdabcd", "x")
'abcdabcd'
>>> myRemove( "abcdabcd", "d")
'abcabcd'
I have tried a few different methods but have not been able to figure the problem out. Here is my attempt:
def myRemove( str, ch ):
for num in range (0, len(str)):
if (str[num] == ch):
return str[0:num] + str[num + 1:]
else:
return str
There is also an extension to this problem which asks : Return a new string with all occurrences of ch removed. If there are none, return str. However, since I have not been able to solve the first part, naturally I was not sure how to solve the second. Would appreciate any guidance.
-
$\begingroup$ This is a question about elementary programming, which is not quite on-topic here. $\endgroup$Yuval Filmus– Yuval Filmus2021年04月03日 09:30:36 +00:00Commented Apr 3, 2021 at 9:30
1 Answer 1
Notice that the loop will only occur once! In the beginning num will be 0. At this point, we enter the if statement:
- if we got that
str[0] == ch(notice thatnum==0and thusstr[0]==str[num]), then we return some string - otherwise we return another string
The important thing here, is that no matter what - we will quit in the first iteration of the for loop.
To fix this, consider placing the return str outside the for loop (without else as well)
-
$\begingroup$ Is it possible for me to make simple modifications which return a new string with all occurrences of ch removed? Or should I should I try to create a while loop? $\endgroup$Obsessive Integer– Obsessive Integer2021年04月02日 23:56:47 +00:00Commented Apr 2, 2021 at 23:56
-
$\begingroup$ There is a (quite simple) modification you can do. Try to think how not to stop only at the first character you see. $\endgroup$nir shahar– nir shahar2021年04月03日 09:25:47 +00:00Commented Apr 3, 2021 at 9:25