How to remove specific characters?
Question:
I want to eliminate specific characters.
I tried the rstrip()
function in Python.
a = "happy! New! Year!!!"
print(a)
b = a.lower()
print(b)
c = b.rstrip('!')
print(c)
This is the result.
happy! New! Year!!!
happy! new! year!!!
happy! new! year
I want to output "happy new year", but the function just got rid of last three ‘!’ characters.
Answers:
The rstrip
function only strips a given character appearing one or more times at the end of the entire string. To remove !
from the end of each word, we can use re.sub
:
a = "happy! New! Year!!!"
output = re.sub(r'b!+(?!S)', '', a)
print(output) # happy New Year
the rstrip function in python will only remove trailing characters that are specified, not all instances of the character in the string. For example if I did:
a = 'hello'
print(a.rstrip('l'))
nothing would change, because there is an e at the end of the string after any instance of ‘l’
You might want to try using the replace method:
a = 'hello'
print(a.replace('l','')
> heo
I want to eliminate specific characters.
I tried the rstrip()
function in Python.
a = "happy! New! Year!!!"
print(a)
b = a.lower()
print(b)
c = b.rstrip('!')
print(c)
This is the result.
happy! New! Year!!!
happy! new! year!!!
happy! new! year
I want to output "happy new year", but the function just got rid of last three ‘!’ characters.
The rstrip
function only strips a given character appearing one or more times at the end of the entire string. To remove !
from the end of each word, we can use re.sub
:
a = "happy! New! Year!!!"
output = re.sub(r'b!+(?!S)', '', a)
print(output) # happy New Year
the rstrip function in python will only remove trailing characters that are specified, not all instances of the character in the string. For example if I did:
a = 'hello'
print(a.rstrip('l'))
nothing would change, because there is an e at the end of the string after any instance of ‘l’
You might want to try using the replace method:
a = 'hello'
print(a.replace('l','')
> heo