35
loading...
This website collects cookies to deliver better user experience
replace()
and translate()
methods. In this tutorial, let’s look at How to remove a character from a string in Python with examples.replace()
methodtransform()
methodreplace()
method replaces the character with a new character. We can use the replace() method to remove a character from a string by passing an empty string as an argument to the replace()
method.**Note:** In Python, strings are immutable, and the **`replace()`** function will return a new string, and the original string will be left unmodified.
# Python program to remove single occurrences of a character from a string
text= 'ItsMyCoode'
print(text.replace('o','',1))
ItsMyCode
**Note:** The count argument in **`replace()`** method indicates the number of times the replacement should be performed in a string.
# Python program to remove all occurrences of a character from a string
text= 'Welcome, to, Python, World'
print(text.replace(',',''))
Welcome to Python World
translate()
* method. The translate()
method accepts one argument, which is a translation table or Unicode code point of a character that you need to replace. ord()
method.None
‘ as a replacement character which in turn removes a specified character from a string as shown below.# Python program to remove a character from a string using translate() method
text= '_User_'
print(text.translate({ord('_'):None}))
User
[:-1]
. The slice notation selects the character at the index position -1 (the last character in a string). Then it returns every character except the last one.# Python program to remove last character from a string using slice notation
text= 'Hello World!'
print(text[:-1])
Hello World
# Python program to remove white spaces from a string
text= 'A B C D E F G H'
# Using replace method
print(text.replace(' ',''))
# Using translate method
print(text.translate({ord(' '):None}))
ABCDEFGH
ABCDEFGH
# Python program to remove punctuation from a string
import string
text= 'Hello, W_orl$d#!'
# Using translate method
print(text.translate(str.maketrans('', '', string.punctuation)))
Hello World