简体   繁体   中英

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#

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

Without regex, simple str.join with a conditional generator:

''.join(c if c in 'nN' else '#' for c in 'BaNana')
# '##N#n#'

Use a negated character class only without a capturing group [^Nn] and replace with # .

No need for using re.MULTILINE as there are no anchors in the pattern.

import re
result = re.sub(r"[^Nn]", "#", "BaNana")
print(result)

Output

##N#n#

Python demo

Although @AlwaysSunny's answer is correct, here is your code fixed:

test_str = ("BaNana")
for x in test_str:
    if x != "n" and x !="N":
        test_str = test_str.replace(x, "#")
    print(test_str)

and the output:

#aNana
##N#n#
##N#n#
##N#n#
##N#n#
##N#n#

Even better would be:

test_str = ("BaNana")
for x in test_str:
    if x != "n" and x !="N":
        test_str = test_str.replace(x, "#")
print(test_str)

for the output:

##N#n#

@schwobaseggl answer is short version of below. In python strings are immutable. So replace function would create new instance of string every time.

test_str = ("BaNana")
temp_list=[]
for x in test_str:
    if x != "n" and  x !="N":
        temp_list.append("#")
    else:
        temp_list.append(x)


new_str= "".join(temp_list)
print(new_str)

From the replace docs:

Return a copy of the string with all occurrences of substring old replaced by new

So for each character you create a new string where this character is replaced. What you can do, is simply add the desired letters and for any other letter add '#' :

test_str = ("BaNana")
ari = ""
for x in test_str:
    if x.lower() == "n":
        ari += x
    else:
        ari += "#"
print(ari)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM