[英]Replace all elements in a string except N, n and spaces in python
我想用# 替换字符串中的所有元素,除了 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#
工作演示: https : //rextester.com/NXW57388
没有正则表达式,简单的str.join
与条件生成器:
''.join(c if c in 'nN' else '#' for c in 'BaNana')
# '##N#n#'
仅使用没有捕获组的否定字符类[^Nn]
并替换为#
。
无需使用re.MULTILINE
因为模式中没有锚点。
import re
result = re.sub(r"[^Nn]", "#", "BaNana")
print(result)
输出
##N#n#
尽管@AlwaysSunny 的回答是正确的,但您的代码已修复:
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#
更好的是:
test_str = ("BaNana")
for x in test_str:
if x != "n" and x !="N":
test_str = test_str.replace(x, "#")
print(test_str)
对于输出:
##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)
从replace
文档:
返回字符串的副本,其中所有出现的子字符串 old 都被 new 替换
因此,对于每个字符,您都会创建一个新字符串,在该字符串中替换该字符。 您可以做的只是添加所需的字母,并为任何其他字母添加'#'
:
test_str = ("BaNana")
ari = ""
for x in test_str:
if x.lower() == "n":
ari += x
else:
ari += "#"
print(ari)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.