In this article, I will introduce 3 ways to remove a specific character from a string in Python.
1. replace()
replace(A, B)
replaces A in a string with B. This can be used to remove certain characters by replacing them with empty(''
).
str = "Hello, World, Python"
new_str = str.replace(',', '')
print(new_str)
Output:
Hello World Python
If you want to delete only the first occurrence of a certain character without deleting all of them, you can pass the number of deletions as the third argument, as in the example below.
str = "Hello, World, Python"
new_str = str.replace(',', '', 1)
print(new_str)
Output:
Hello World, Python
In addition, you can delete not only characters but also strings as follows.
str = "Hello, World, Python"
new_str = str.replace('World,', '')
print(new_str)
Output:
Hello, Python
2. Regex
sub(regex, replacement, str)
finds the regex pattern in the string and replaces the corresponding part with the replacement. This can be used to delete specific characters.
In this example, it replaces ,
with empty(""
) to remove it.
import re
str = "Hello, World, Python"
result = re.sub(",", "", str)
print(result)
Output:
Hello World Python
The example below removes all occurrences of the string ,
, He
and Py
. In this pattern, the |
is used to add multiple patterns, like meaning OR.
import re
str = "Hello, World, Python"
result = re.sub(",|He|Py", "", str)
print(result)
Output:
llo World thon
3. for loop
You can implement a code to directly delete a specific character using a loop. When you loop through the string like for char in str
, you traverse each character.
The example below removes the character if it is one of HWP
by using the replace function. By doing this for all characters, you can confirm that the desired string has been completely deleted.
str = "Hello, World, Python"
result = str
for char in str:
if char in "HWP":
result = result.replace(char, '')
print(result)
Output:
ello, orld, ython
Related Posts
- Convert list to set in Python
- 3 Ways to Remove character from a string in Python
- Append an item to the front of list in Python
- Difference between append, extend and insert in Python
- Python - String strip (), rstrip (), lstrip ()
- Python - String Formatting Best Practices (%, str formatting, f-stirng)
- Import python modules in different directories.
- Dynamic import in Python (Reflection in Python)