Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a character from a string using Python

Tags:

python

string

There is a string, for example. EXAMPLE.

How can I remove the middle character, i.e., M from it? I don't need the code. I want to know:

  • Do strings in Python end in any special character?
  • Which is a better way - shifting everything right to left starting from the middle character OR creation of a new string and not copying the middle character?
like image 780
Lazer Avatar asked Aug 24 '10 18:08

Lazer


People also ask

How do I remove a character from a string in Python?

Using translate(): translate() is another method that can be used to remove a character from a string in Python. translate() returns a string after removing the values passed in the table. Also, remember that to remove a character from a string using translate() you have to replace it with None and not "" .

How do you get rid of a character in a string?

Use the deleteCharAt Method to Remove a Character From String in Java. The deleteCharAt() method is a member method of the StringBuilder class that can also be used to remove a character from a string in Java.


2 Answers

To replace a specific position:

s = s[:pos] + s[(pos+1):] 

To replace a specific character:

s = s.replace('M','') 
like image 22
Eton B. Avatar answered Nov 01 '22 08:11

Eton B.


In Python, strings are immutable, so you have to create a new string. You have a few options of how to create the new string. If you want to remove the 'M' wherever it appears:

newstr = oldstr.replace("M", "") 

If you want to remove the central character:

midlen = len(oldstr) // 2 newstr = oldstr[:midlen] + oldstr[midlen+1:] 

You asked if strings end with a special character. No, you are thinking like a C programmer. In Python, strings are stored with their length, so any byte value, including \0, can appear in a string.

like image 59
Ned Batchelder Avatar answered Nov 01 '22 08:11

Ned Batchelder