I know how to remove the first occurrence of a letter using splicing, but I'm trying to achieve this without using any of the string functions like splicing, .find(), .count(), etc. I can't seem to figure out how you complete it without splicing.
Here's what I currently have with splicing that works correctly:
s1 = ''
s2 = len(remWord)
for i in range(s2):
if (remWord[i] == remLetter):
s1 = remWord[0:i] + remWord[i + 1:s2]
return s1
Any assistance would be great.
remove() This method removes first occurrence given element from the list.
The remove() method will remove the first instance of a value in a list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.
The idea is to use charAt() method of String class to find the first and last character in a string. The charAt() method accepts a parameter as an index of the character to be returned. The first character in a string is present at index zero and the last character in a string is present at index length of string-1 .
I am assuming that you do not remove anything if the letter is not contained in the string, so you can use the following code:
new_string = ''
found = False
for i in range(len(remWord)):
if remWord[i] != remLetter or found:
new_string += remWord[i]
else:
found = True
new_string = ''
for i in range(len(remWord)):
if remWord[i] != remLetter:
new_string += remWord[i]
else:
break
new_string += remWord[i + 1:]
You should stop the processing as soon as you encounter the first letter, use a break
for this purpose.
remWord = 'this is the word to process'
remLetter = 's'
s1 = ''
s2 = len(remWord)
for i in range(s2):
if (remWord[i] == remLetter):
s1 = remWord[0:i] + remWord[i + 1:s2]
break
print s1
output:
$ python firstletter.py
thi is the word to process
If you omit the break
, your output will be like this
$ python firstletter.py
this is the word to proces
As the if clause will be satisfied for the last encounter of the remLetter
present in your input string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With