0
$\begingroup$

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.

asked Apr 2, 2021 at 23:21
$\endgroup$
1
  • $\begingroup$ This is a question about elementary programming, which is not quite on-topic here. $\endgroup$ Commented Apr 3, 2021 at 9:30

1 Answer 1

2
$\begingroup$

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 that num==0 and thus str[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)

answered Apr 2, 2021 at 23:29
$\endgroup$
2
  • $\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$ Commented 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$ Commented Apr 3, 2021 at 9:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.