565

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?
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lazer
  • 90,700
  • 113
  • 281
  • 364

17 Answers17

780

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.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 18
    Given that the questioner is brand new to python, it might be worth noting that while in version 2.X python the "/" operator returns an integer (truncated towards zero), in version 3.X python you should use "//" instead. Also, the line `from __future__ import division` at the beginning of your script will make version 2.X python act like version 3.X – Michael Dunn Aug 24 '10 at 20:29
  • 1
    Note that if "M" is the only contents of the line, "" leaves behind an empty line in its place. – 8bitjunkie Aug 13 '15 at 22:50
  • 1
    @7SpecialGems it depends entirely on what you do with this string. An empty string like `""` doesn't imply an empty line. If you put it in a list, and join it with newlines, then it will make an empty line, but there are lots of other places you might use an empty string that won't do that. – Ned Batchelder Aug 14 '15 at 10:06
  • 1
    [Under the hood](https://github.com/python/cpython/blob/b063b02eabf91bfd4edc0f3fde7ce8f0ebb392c4/Include/cpython/unicodeobject.h#L228), strings in Python are also null terminated but that doesn't matter. – Boris Verkhovskiy May 08 '21 at 10:01
89

To replace a specific position:

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

To replace a specific character:

s = s.replace('M','')
Eton B.
  • 6,121
  • 5
  • 31
  • 43
  • 20
    While this may work, I think your answer could be improved by explaining what is going on in the first part, since the substring operations are not necessarily easy to understand for a Python newbie without any explanation. – jloubert Aug 24 '10 at 19:44
  • So if the length of s is `l`. Then for the first part, the constraint for pos should be `l-1 > pos >= 0`. – Haoyu Chen Apr 11 '15 at 17:28
  • s[:pos] gets substring from 0 to pos-1 and s[(pos+1):] gets substring from pos+1 to end. Hence, it removes s[pos] from s. – s.singh Sep 10 '19 at 12:23
  • its not replacing, it dropping. its good to distinguish the operation by providing examples for both of the two major uses cases, separated by their position selection method. – Alexander Stohr Mar 17 '20 at 15:29
85

This is probably the best way:

original = "EXAMPLE"
removed = original.replace("M", "")

Don't worry about shifting characters and such. Most Python code takes place on a much higher level of abstraction.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
recursive
  • 83,943
  • 34
  • 151
  • 241
38

Strings are immutable. But you can convert them to a list, which is mutable, and then convert the list back to a string after you've changed it.

s = "this is a string"

l = list(s)  # convert to list

l[1] = ""    # "delete" letter h (the item actually still exists but is empty)
l[1:2] = []  # really delete letter h (the item is actually removed from the list)
del(l[1])    # another way to delete it

p = l.index("a")  # find position of the letter "a"
del(l[p])         # delete it

s = "".join(l)  # convert back to string

You can also create a new string, as others have shown, by taking everything except the character you want from the existing string.

kindall
  • 178,883
  • 35
  • 278
  • 309
12

Use the translate() method:

>>> s = 'EXAMPLE'
>>> s.translate(None, 'M')
'EXAPLE'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
  • 4
    The method has changed. See the docs for Python 3: [translate()](https://docs.python.org/3/library/stdtypes.html#str.translate) This replaces different characters with space (`None` to remove seems not to work): `translate( str.maketrans("<>", " ") )` – handle May 20 '14 at 07:04
  • 1
    Actually, the docs specify two ways to remove different characters with translate() in Python 3, : `str.maketrans( "", "", "<>")` and `str.maketrans( {"<":None,">":None })` – handle May 20 '14 at 07:40
  • 4
    The equivalent of the code in the answer became this in python3: `'EXAMPLE'.translate({ord("M"): None})` – yoniLavi Dec 09 '15 at 18:29
12

How can I remove the middle character, i.e., M from it?

You can't, because strings in Python are immutable.

Do strings in Python end in any special character?

No. They are similar to lists of characters; the length of the list defines the length of the string, and no character acts as a terminator.

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?

You cannot modify the existing string, so you must create a new one containing everything except the middle character.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Richard Fearn
  • 25,073
  • 7
  • 56
  • 55
9
def kill_char(string, n): # n = position of which character you want to remove
    begin = string[:n]    # from beginning to n (n not included)
    end = string[n+1:]    # n+1 through end of string
    return begin + end
print kill_char("EXAMPLE", 3)  # "M" removed

I have seen this somewhere here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1443297
  • 91
  • 1
  • 1
6
card = random.choice(cards)
cardsLeft = cards.replace(card, '', 1)

How to remove one character from a string: Here is an example where there is a stack of cards represented as characters in a string. One of them is drawn (import random module for the random.choice() function, that picks a random character in the string). A new string, cardsLeft, is created to hold the remaining cards given by the string function replace() where the last parameter indicates that only one "card" is to be replaced by the empty string...

6

On Python 2, you can use UserString.MutableString to do it in a mutable way:

>>> import UserString
>>> s = UserString.MutableString("EXAMPLE")
>>> type(s)
<class 'UserString.MutableString'>
>>> del s[3]    # Delete 'M'
>>> s = str(s)  # Turn it into an immutable value
>>> s
'EXAPLE'

MutableString was removed in Python 3.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
killown
  • 4,497
  • 3
  • 25
  • 29
3

Another way is with a function,

Below is a way to remove all vowels from a string, just by calling the function

def disemvowel(s):
    return s.translate(None, "aeiouAEIOU")
Kyoujin
  • 315
  • 1
  • 5
  • 19
  • 4
    do you mean `s.translate(str.maketrans("", "", "aeiouAEIOU"))`? – Dyno Fu Jul 07 '20 at 23:56
  • @DynoFu I think that's what he meant, because your answer is the only one which makes sense in this whole thread. All others get very complicated if you need to remove additional characters. – not2qubit Nov 09 '20 at 23:11
2

Here's what I did to slice out the "M":

s = 'EXAMPLE'
s1 = s[:s.index('M')] + s[s.index('M')+1:]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PaulM
  • 29
  • 1
2

To delete a char or a sub-string once (only the first occurrence):

main_string = main_string.replace(sub_str, replace_with, 1)

NOTE: Here 1 can be replaced with any int for the number of occurrence you want to replace.

BlackBeard
  • 10,246
  • 7
  • 52
  • 62
2

You can simply use list comprehension.

Assume that you have the string: my name is and you want to remove character m. use the following code:

"".join([x for x in "my name is" if x is not 'm'])
hubert
  • 2,997
  • 3
  • 20
  • 26
1

If you want to delete/ignore characters in a string, and, for instance, you have this string,

"[11:L:0]"

from a web API response or something like that, like a CSV file, let's say you are using requests

import requests
udid = 123456
url = 'http://webservices.yourserver.com/action/id-' + udid
s = requests.Session()
s.verify = False
resp = s.get(url, stream=True)
content = resp.content

loop and get rid of unwanted chars:

for line in resp.iter_lines():
  line = line.replace("[", "")
  line = line.replace("]", "")
  line = line.replace('"', "")

Optional split, and you will be able to read values individually:

listofvalues = line.split(':')

Now accessing each value is easier:

print listofvalues[0]
print listofvalues[1]
print listofvalues[2]

This will print

11

L

0

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
d1jhoni1b
  • 7,497
  • 1
  • 51
  • 37
1

Two new string removal methods are introduced in Python 3.9+

#str.removeprefix("prefix_to_be_removed")
#str.removesuffix("suffix_to_be_removed")

s='EXAMPLE'

In this case position of 'M' is 3

s = s[:3] + s[3:].removeprefix('M')

OR

s = s[:4].removesuffix('M') + s[4:]

#output'EXAPLE'
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
0
from random import randint


def shuffle_word(word):
    newWord=""
    for i in range(0,len(word)):
        pos=randint(0,len(word)-1)
        newWord += word[pos]
        word = word[:pos]+word[pos+1:]
    return newWord

word = "Sarajevo"
print(shuffle_word(word))
  • 2
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – andreas Oct 17 '16 at 22:41
-8

Strings are immutable in Python so both your options mean the same thing basically.

Skilldrick
  • 69,215
  • 34
  • 177
  • 229