在python中替换字符串中除N、N和空格以外的所有元素
我想用#替换字符串中除N和N之外的所有元素。这是我一直在工作的代码在python中替换字符串中除N、N和空格以外的所有元素,python,if-statement,replace,Python,If Statement,Replace,我想用#替换字符串中除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# 您可
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#
工作演示:来自文档:
返回包含所有子字符串old的字符串副本
换成新的
因此,为每个字符创建一个新字符串,替换该字符。您只需添加所需的字母,对于任何其他字母,请添加“#”
:
test_str=(“香蕉”)
ari=“”
对于测试中的x_str:
如果x.lower()=“n”:
ari+=x
其他:
ari+=“#”
打印(ari)
仅在没有捕获组的情况下使用否定字符类[^Nn]
并替换为
无需使用re.MULTILINE
,因为模式中没有锚定
import re
result = re.sub(r"[^Nn]", "#", "BaNana")
print(result)
输出
##N#n#
尽管@AlwaysAnny的答案是正确的,但下面是您的代码:
test_str = ("BaNana")
for x in test_str:
if x != "n" and x !="N":
test_str = test_str.replace(x, "#")
print(test_str)
以及输出:
#aNana
##N#n#
##N#n#
##N#n#
##N#n#
##N#n#
##N#n#
更好的办法是:
test_str = ("BaNana")
for x in test_str:
if x != "n" and x !="N":
test_str = test_str.replace(x, "#")
print(test_str)
对于输出:
#aNana
##N#n#
##N#n#
##N#n#
##N#n#
##N#n#
##N#n#
没有正则表达式,使用条件生成器简单地
str.join
:
''.join(c if c in 'nN' else '#' for c in 'BaNana')
# '##N#n#'
@Schwobasegll的答案是下面的简短版本。在python中,字符串是不可变的。所以
replace
函数每次都会创建新的字符串实例
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)
!(n或n)
与相同!n和!N
,而不是!n或!N
。请参见'N'
不等于'N'
,因此您将为这两个字母中的任何一个输入