2017-12-03 6 views
1

最初の文字列を変更せずに、各文字の2番目の文字を "@"に変更するPythonコードを作成したい。 :文字列中のすべての繰り返し文字を "@"に変更するPythonコードを書く。

"Pythonが良いプロトタイピング言語である" と私は、次のコードを書かれている

"Pythonはグラム@@ D @r @@@@@@ラ@@ U @@ Eです"それは動作しません。

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

それを動作させる方法を教えてください 事前に感謝!

答えて

3

あなたはこれを試すことができます:少なくとも長い入力のために、

シンプル、あまりパフォーマンス

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 [email protected]@d [email protected]@@@@@@@@ [email protected]@[email protected]@e' 

でもソーターソリューション:

new_s = ''.join('@' if a in s[:i] and a != ' ' else a for i, a in enumerate(s)) 

出力:

'Python is [email protected]@d [email protected]@@@@@@@@ [email protected]@[email protected]@e' 
3

は、次の操作を行うことができます。

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

また、前の文字のためのリストで直接チェックすることができますが、セットは良く含まれ、チェックされています。同様に、文字列を直接アセンブルすることもできますが、リストのappendは不変文字列の+=よりもパフォーマンスが優れています。

text = input("please enter some text ") 
s = '' 
for c in text: 
    s += c if c not in s or c == ' ' else '@' 
print(s) 
+0

はい、二倍以下:1)文字列を変更し、2)「セット」しません。いい答えだ。 –

+0

@ Jean-FrançoisFabreでも、より複雑なデータ構造のオーバーヘッドを相殺するために、入力にいくつかの文字が必要であると思います。 – schwobaseggl

2

私はそれがオフビートの代替だだけで、これは良いですが主張していませんよ。

>>> 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 [email protected]@@[email protected]@@@@@@@@@@[email protected]@[email protected]@e' 
関連する問題