2012-02-26 8 views
110

string.replace()はPython 3.xでは非推奨です。これを行う新しい方法は何ですか?python 3.xでstring.replace()を使用する方法

+9

FWIW、私は同じ混乱がありました。 Googleの "python string replace"は、Python 2.7で廃止予定の古い文字列関数に私を連れて行きました。 IMHOでは、このセクションでは、 "string.xxx()"と "xxx(string)"を説明する大胆なボックスを使用して、非推奨のストリングメソッドに人を誘導することができます。 http://docs.python.org/library/stdtypes.html#string-methods – ToolmakerSteve

+1

Pythonのドキュメントは、それが理想的な第一言語として宣伝されていることを考慮すると絶対的な騒ぎです。非常に頻繁にそこにあるが、貧弱な方法のために編成され、頻繁に検索エンジンや自分のサイトでもよく索引付けされていない。 ToolMakerSteveのリンクを見ると、コア文字列関数は標準型にルーピングされています。これは、文字列関数を検索するときには発生しません。 –

答えて

126

str.replace()を使用します。

例:

>>> 'Hello world'.replace('world', 'Guido') 
'Hello Guido' 
+3

"re"(正規表現)モジュールには、非推奨の文字列関数(いくつかのすべて?)の代替があります。この場合、 're.sub()'となります。 – ToolmakerSteve

+3

@ToolmakerSteve: 'string'関数は非難されています。 'str'メソッドはそうではありません。 –

+0

oooh。私は間違っていた。ありがとう! – ToolmakerSteve

78

replace()はのpython3で<class 'str'>する方法であって、2.xで同様

>>> 'hello, world'.replace(',', ':') 
'hello: world' 
3

これを試してみてください:

FYI
mystring = "This Is A String" 
print(mystring.replace("String","Text")) 
1

は、文字列内の任意の位置に固定された単語に一部の文字を追加する場合(例えば副詞に形容詞を変更接尾辞-lyを追加することにより、接尾辞を末尾に付けて読みやすくすることができます。これを行うには、replace()split()を使用します。

s="The dog is large small" 
ss=s.replace(s.split()[3],s.split()[3]+'ly') 
ss 
'The dog is largely small' 
-4
ss = s.replace(s.split()[1], +s.split()[1] + 'gy') 
# should have no plus after the comma --i.e., 
ss = s.replace(s.split()[1], s.split()[1] + 'gy') 
+3

このコードは質問に答えるかもしれませんが、理由や質問にどう答えるかに関する追加の文脈を提供することで、長期的な価値が大幅に向上します。あなたの答えを[編集]して、説明を加えてください。 – CodeMouse92

0

をパイソン3でreplace()メソッドは、単純で使用されます。

a = "This is the island of istanbul" 
print (a.replace("is" , "was" , 3)) 

#3 is the maximum replacement that can be done in the string# 

>>> Thwas was the wasland of istanbul 

# Last substring 'is' in istanbul is not replaced by was because maximum of 3 has already been reached 
+0

3を置くこともできず、すべての偶然が変更されることに注意してください。 –

+0

はい、これはオプションです。 :) –

関連する問題