Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove first occurrence of a letter?

Tags:

python

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.

like image 833
Denis Johnson Avatar asked Mar 06 '19 03:03

Denis Johnson


People also ask

How do I get rid of first occurrence?

remove() This method removes first occurrence given element from the list.

How do you remove first instance of an item from a 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.

How do I find the first and last occurrence of a character in a string?

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 .


2 Answers

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:

Strictly not using splicing

new_string = ''
found = False

for i in range(len(remWord)):
    if remWord[i] != remLetter or found:
        new_string += remWord[i]
    else:
        found = True

If you are allowed to use splicing

new_string = ''

for i in range(len(remWord)):
    if remWord[i] != remLetter:
        new_string += remWord[i]
    else:
        break

new_string += remWord[i + 1:]
like image 53
lmiguelvargasf Avatar answered Nov 04 '22 17:11

lmiguelvargasf


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

like image 31
Allan Avatar answered Nov 04 '22 15:11

Allan