我想制作一个python代码,将每个字符的第二个出现更改为"@",而不会更改第一次出现,例如:
" Python是好原型语言"至" Python是G @@@@d @r @@@@@@@@@@ la @@ u @@ u @@ e"
我编写了以下代码,但它不起作用
text = input ( "please enter some text ")
for i in range(len(text)):
abc = text[i]
text.replace(abc,"@")
print(text)
请告诉我如何使它起作用预先感谢!
您可以尝试以下方法:
s = 'Python is good prototyping language'
seen = []
new_s = ''
for i in s:
if i not in seen:
new_s += i
seen.append(i)
else:
if i != ' ':
new_s += "@"
else:
new_s += ' '
输出:
'Python is g@@d pr@@@@@@@@@ la@@u@@e'
甚至分类器解决方案:
new_s = ''.join('@' if a in s[:i] and a != ' ' else a for i, a in enumerate(s))
输出:
'Python is g@@d pr@@@@@@@@@ la@@u@@e'
您可以执行以下操作:
text = input("please enter some text ")
l, seen = [], set()
for c in text:
if c in seen and c != ' ':
l.append("@")
else:
l.append(c)
seen.add(c)
print(''.join(l))
您也可以在列表中直接检查以前的字符,但是一组具有更好的检查检查。同样,您可以直接组装一个字符串,但是List的append
比不变的字符串的+=
具有更好的性能。
更简单,但性能较少,至少对于长输入:
text = input("please enter some text ")
s = ''
for c in text:
s += c if c not in s or c == ' ' else '@'
print(s)
我不是声称这是好的,只是它是另一种替代方案。
>>> s = "Python is good prototyping language"
>>> class Replacer(dict):
... def __missing__(self, key):
... self[key]='@'
... return key
...
>>> replacer = Replacer()
>>> ''.join([replacer[c] for c in s])
'Python is@g@@d@pr@@@@@@@@@@la@@u@@e'