Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all elements in a string except N, n and spaces in python

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#
like image 809
Derpyninja Avatar asked Mar 04 '26 23:03

Derpyninja


1 Answers

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

like image 93
Always Sunny Avatar answered Mar 06 '26 12:03

Always Sunny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!