我想用 # 替换字符串中除 N 和 n 之外的所有元素。这是我一直在工作的代码
test_str = ("BaNana")
for x in test_str:
if x != "n" or x !="N":
ari = test_str.replace(x, "#")
print(ari)
我得到的输出是
#aNana
B#N#n#
Ba#ana
B#N#n#
B#N#n#
我想要的输出是
##N#n#
最佳答案
您可以使用字符类[^Nn]
以及前面的否定运算符^
来替换每个字符除了 N
和 n
如下所示,
import re
regex = r"([^Nn])"
test_str = "BaNana"
subst = "#"
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
输出
##N#n#
关于python - 替换python中除N、n和空格之外的字符串中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59227098/