[英]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.我想用# 替换字符串中的所有元素,除了 N 和 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,您可以使用字符类
[^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)
OUTPUT输出
##N#n#
WORKING DEMO: https://rextester.com/NXW57388工作演示: https : //rextester.com/NXW57388
Without regex, simple str.join
with a conditional generator:没有正则表达式,简单的
str.join
与条件生成器:
''.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 #
.仅使用没有捕获组的否定字符类
[^Nn]
并替换为#
。
No need for using re.MULTILINE
as there are no anchors in the pattern.无需使用
re.MULTILINE
因为模式中没有锚点。
import re
result = re.sub(r"[^Nn]", "#", "BaNana")
print(result)
Output输出
##N#n#
Although @AlwaysSunny's answer is correct, here is your code fixed:尽管@AlwaysSunny 的回答是正确的,但您的代码已修复:
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. @schwobaseggl 答案是以下的简短版本。 In python strings are immutable.
在python中字符串是不可变的。 So
replace
function would create new instance of string every time.所以
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)
From the replace
docs:从
replace
文档:
Return a copy of the string with all occurrences of substring old replaced by new
返回字符串的副本,其中所有出现的子字符串 old 都被 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.