How to Delete a Character from a String Using Python

How to delete a character from a string using Python

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.

Remove specific characters from a string in Python

Strings in Python are immutable (can't be changed). Because of this, the effect of line.replace(...) is just to create a new string, rather than changing the old one. You need to rebind (assign) it to line in order to have that variable take the new value, with those characters removed.

Also, the way you are doing it is going to be kind of slow, relatively. It's also likely to be a bit confusing to experienced pythonators, who will see a doubly-nested structure and think for a moment that something more complicated is going on.

Starting in Python 2.6 and newer Python 2.x versions *, you can instead use str.translate, (see Python 3 answer below):

line = line.translate(None, '!@#$')

or regular expression replacement with re.sub

import re
line = re.sub('[!@#$]', '', line)

The characters enclosed in brackets constitute a character class. Any characters in line which are in that class are replaced with the second parameter to sub: an empty string.

Python 3 answer

In Python 3, strings are Unicode. You'll have to translate a little differently. kevpie mentions this in a comment on one of the answers, and it's noted in the documentation for str.translate.

When calling the translate method of a Unicode string, you cannot pass the second parameter that we used above. You also can't pass None as the first parameter. Instead, you pass a translation table (usually a dictionary) as the only parameter. This table maps the ordinal values of characters (i.e. the result of calling ord on them) to the ordinal values of the characters which should replace them, or—usefully to us—None to indicate that they should be deleted.

So to do the above dance with a Unicode string you would call something like

translation_table = dict.fromkeys(map(ord, '!@#$'), None)
unicode_line = unicode_line.translate(translation_table)

Here dict.fromkeys and map are used to succinctly generate a dictionary containing

{ord('!'): None, ord('@'): None, ...}

Even simpler, as another answer puts it, create the translation table in place:

unicode_line = unicode_line.translate({ord(c): None for c in '!@#$'})

Or, as brought up by Joseph Lee, create the same translation table with str.maketrans:

unicode_line = unicode_line.translate(str.maketrans('', '', '!@#$'))

* for compatibility with earlier Pythons, you can create a "null" translation table to pass in place of None:

import string
line = line.translate(string.maketrans('', ''), '!@#$')

Here string.maketrans is used to create a translation table, which is just a string containing the characters with ordinal values 0 to 255.

How to delete character from a string?

Answer to the question

Don't use the name str for your string variable. It will mask the built-in str:

intab = "0123456789"
outtab = intab[::-1]
trantab = str.maketrans(intab, outtab)
mystring = "p1y2t3h4o5n6"
print(mystring.translate(trantab))

Output:

p8y7t6h5o4n3

Your intab and outtab must have the same length. Most functions from string in Python 2 became methods of str for a while in Python 2 and were dropped as functions from string in Python 3. So use str.maketrans().

Solving the problem

If want to remove characters from a string you can do:

remove = set("0123456789")
mystring = "p1y2t3h4o5n6"
print(''.join(x for x in mystring if x not in remove))

Output:

python

If you want to remove numbers you can also do:

print(''.join(x for x in mystring if not x.isdigit()))

Output:

python

How do I remove a substring from the end of a string?

strip doesn't mean "remove this substring". x.strip(y) treats y as a set of characters and strips any characters in that set from both ends of x.

On Python 3.9 and newer you can use the removeprefix and removesuffix methods to remove an entire substring from either side of the string:

url = 'abcdc.com'
url.removesuffix('.com') # Returns 'abcdc'
url.removeprefix('abcdc.') # Returns 'com'

The relevant Python Enhancement Proposal is PEP-616.

On Python 3.8 and older you can use endswith and slicing:

url = 'abcdc.com'
if url.endswith('.com'):
url = url[:-4]

Or a regular expression:

import re
url = 'abcdc.com'
url = re.sub('\.com$', '', url)

Deleting a character at specified index position in a string using python

pop does not operate on a string, but even if it did it would return the item it deleted. There are several ways to do this, one, using pop, creates a list then converts back to a string:

st = "hello"
n = int(input())

def drop_n(st, n):
if n < len(st): # note the change to this.
it = list(st)
char = it.pop(n)
return ''.join(it)
else:
return "String too small or number too big"

print(drop_n(st, n))

Note that negative indices are valid. n == len(st) would go beyond the bounds of the list, since indices count from zero.

How to delete the following characters in a string with python?

There are a few ways to choose from as the existing answers demonstrate. Another way, if these characters always come at the end, could be to just split your string on the '.' character and keep the first section:

stock = 'RS2K.SW'
new_string = stock.split(.)[0]

Python best way to remove char from string by index

You can bypass all the list operations with slicing:

S = S[:1] + S[2:]

or more generally

S = S[:Index] + S[Index + 1:]

Many answers to your question (including ones like this) can be found here: How to delete a character from a string using python?. However, that question is nominally about deleting by value, not by index.

How to remove all characters before a specific character in Python?

Use re.sub. Just match all the chars upto I then replace the matched chars with I.

re.sub(r'^.*?I', 'I', stri)


Related Topics



Leave a reply



Submit