2017-04-13 13 views
-1

私は文字列を配列していますが、いくつか置き換えたいと思います。たとえば:文字列内の文字を新しい単語に置き換えます。

my_strings = [['hi/hello world &'], ['hi/hello world'], ['it\90s the world'], ['hello world'], ['hello "world"']] 

new_strings = [['hi and hello world'], ['hi and hello world'], ["it's the world"], ['hello world'], ['hello world']] 

はどのようにして置き換えることができます/として、配列内の文字列は、これらの文字が含まれている場合、言葉の周りに「」&と\ 90を削除し、削除しますか?その記事で見られるように

+2

HTTPS

my_replacement_dict = { "/": "and", "&": "", # Empty string to remove the word "\90": "", "\"": "" } 

は次に、目的のリストを取得するにはあなたのリストとのdict以上を踏まえreplace言葉を反復処理します://www.tutorialspoint.com/python/string_replace.htm – oshaiken

+0

公式ドキュメントのreplaceメソッドをご覧ください:https://docs.python.org/2/library/string.html –

+0

実際には、文字列の配列はありません。あなたの誤称を使って(配列ではなく "リスト"でなければなりません)、配列の配列があります。各文字列のまわりに余分な '['と ']'がある理由はありますか? –

答えて

2

最初にdictオブジェクトを作成して、その単語を置き換えてマップする必要があります。たとえば:

my_list = [['hi/hello world &'], ['hi/hello world'], ['it\90s the world'], ['hello world'], ['hello "world"']] 
new_list = [] 

for sub_list in my_list: 
    # Fetch string at `0`th index of nested list 
    my_str = sub_list[0] 
    # iterate to get `key`, `value` from replacement dict 
    for key, value in my_replacement_dict.items(): 
     # replace `key` with `value` in the string 
     my_str = my_str.replace(key, value) 
    new_list.append([my_str]) # `[..]` to add string within the `list` 
new_list

最終内容は次のようになります:

>>> new_list 
[['hi and hello world '], ['hi and hello world'], ['its the world'], ['hello world'], ['hello world']] 
+0

OPの質問で判断すると、Pythonには新しいかもしれません。あなたのコードでもう少し詳しく説明できますか?例えば ​​'sub_list [0]'を呼び出す理由を説明してください。それは、あなたが各サブリストのインデックス0を呼び出していること、なぜそれをやっているのかを知るために役立つかもしれません。 –

+0

@BaconTechフェア十分です。コメントを追加しました –

関連する問題