25
Remove Character From String Python
ItsMyCode |
We can remove a character from String in Python using replace()
and translate()
methods. In this tutorial, let’s look at How to remove a character from a string in Python with examples.
There are many scenarios where we need to replace all occurrences of a character from a string or remove a specific character from a string. The two recommended approaches are :
- Using the
replace()
method - Using the
transform()
method
The replace()
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.
If you want to remove the first occurrence of a character from a string, then you can use pass a count argument as 1 to the replace method, as shown below.
# Python program to remove single occurrences of a character from a string
text= 'ItsMyCoode'
print(text.replace('o','',1))
Output
ItsMyCode
**Note:** The count argument in **`replace()`** method indicates the number of times the replacement should be performed in a string.
If you want to remove all the occurrences of a character from a string, then you can exclude the count argument as shown below.
# Python program to remove all occurrences of a character from a string
text= 'Welcome, to, Python, World'
print(text.replace(',',''))
Output
Welcome to Python World
The other alternative is to use the*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.
We can get the Unicode code point of any character using theord()
method.
You need to map ‘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}))
Output
User
If you want to remove the last character from a string in Python, you can use slice notation [:-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])
Output
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}))
Output
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)))
Output
Hello World
The post Remove Character From String Python appeared first on ItsMyCode.
25