Home > Article > Backend Development > How do you remove a character from a string in Python?
Deleting a Character from a String in Python
Strings in Python are immutable sequences of characters, unlike C-strings, which are terminated by a null character. Therefore, removing a character from a string in Python requires creating a new string.
Removing Specific Character Instances
To remove all instances of a specific character from a string, the replace() method can be used:
<code class="python">newstr = oldstr.replace("character", "")</code>
For instance, to remove all occurrences of the letter "M" from the string "EXAMPLE", the following code can be used:
<code class="python">newstr = "EXAMPLE".replace("M", "")</code>
Removing a Character at a Specific Index
If the goal is to remove the character at a specific index, a new string can be created by concatenating the portions of the original string before and after the index to be removed:
<code class="python">midlen = len(oldstr) // 2 newstr = oldstr[:midlen] + oldstr[midlen + 1:]</code>
This approach avoids shifting the characters to the left or right.
Additional Considerations
Unlike in C, strings in Python are not stored with a termination character. Therefore, any value, including the null character (
The above is the detailed content of How do you remove a character from a string in Python?. For more information, please follow other related articles on the PHP Chinese website!