I want to replace all elements in a string with a # except for N and n. This is the code that i have been working
test_str = ("BaNana")
for x in test_str:
if x != "n" or x !="N":
ari = test_str.replace(x, "#")
print(ari)
The output that i get is
#aNana
B#N#n#
Ba#ana
B#N#n#
B#N#n#
Where as the output that i want is
##N#n#
You can use character class [^Nn] with the preceeding negation operator ^ to replace every character except N and n like below,
import re
regex = r"([^Nn])"
test_str = "BaNana"
subst = "#"
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
OUTPUT
##N#n#
WORKING DEMO: https://rextester.com/NXW57388
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With