In this tutorial, we will look at how to remove the first occurrence of a character from a string in Python with the help of some examples.
How to remove the first instance of a character in a string?

Strings are immutable in Python. That is, they cannot be modified after they are created. You can, however, create a copy of the original string with the first occurrence of the character removed.
To remove the first occurrence of a character from a string –
- Use the string
index()
function to get the index of the first occurrence. Note that if the character is not present in the string, it will raise aValueError
. - Then, use the above index to slice the original string such that the character at that index is skipped.
Let’s look at an example –
# create a string s = "Two cryons, a pen, a pencil, and a sharpner." # get index of first occurrence of 'a' i = s.index('a') # remove the first occurrence of 'a' print(s[:i]+s[i+1:])
Output:
Two cryons, pen, a pencil, and a sharpner.
You can see that the output string does not contain the first occurrence of the character ‘a’ from the original string. Also, notice that the other occurrences of the character ‘a’ in the string are unaffected.
For more on the Python string index() function, refer to its documentation.
Using a Loop to remove the first occurrence of character in String
Alternatively, you can also use a loop to iterate through the characters of the original string and remove the first occurrence of a character from a string in Python. Use the following steps –
- Create an empty string to store our result and a flag set to
False
to determine whether we have encountered the character that we want to remove. - Iterate through each character in the original string.
- For each character, check if it’s equal to the character we want to remove and whether the flag is
False
. If both the conditions are true, set the flag toTrue
and skip over to the next iteration. Else, add the character to our result string.
Let’s look at an example –
# create a string s = "Two cryons, a pen, a pencil, and a sharpner." result = "" ch_to_remove = 'a' occurred_flag = False # iterate over each character in s for ch in s: if ch == ch_to_remove and occurred_flag == False: occurred_flag = True continue else: result += ch # display the resulting string print(result)
Output:
Two cryons, pen, a pencil, and a sharpner.
We get the same result as above. The resulting string has the first instance of the character removed.
You might also be interested in –
- Python – Remove the First Word From String
- Python – Remove First N Characters From String
- Remove First Character From String in Python
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.