我想用#代替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#
@schwobaseggl答案是下面的简短版本。在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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句