编写python代码,将字符串中所有重复的字符改为“@”,除了第一次出现的字符

2024-06-26 01:38:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想制作一个python代码,将每个字符的第二个匹配项更改为“@”,而不更改第一个匹配项,如:

"Python is good prototyping language" to "Python is g@@d @r@@@@@@ la@@u@@e"

我已经写了下面的代码,但它不工作

text = input ( "please enter some text ")
for i in range(len(text)):
    abc = text[i]
    text.replace(abc,"@")
print(text)

请告诉我怎么做 提前谢谢


Tags: to代码textforinputissome字符
3条回答

我并不是说这是好的,只是说这是一个另类的选择

>>> 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'

您可以执行以下操作:

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))

您也可以直接在列表中检查以前的字符,但是集合具有更好的contains检查。类似地,可以直接组装字符串,但是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'
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'

相关问题 更多 >