2017-04-13 125 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 ://www.tutorialspoint.com/python/string_replace.htm – oshaiken

+0

查看官方文檔中的替換方法:https://docs.python.org/2/library/string.html –

+0

實際上,你沒有一個字符串數組。使用你的用詞不當(它應該是「列表」,而不是「數組」),你有一個字符串數組的數組。是否有任何理由爲每個字符串附加額外的'['和']'? –

回答

2

首先,您應該創建一個dict對象來映射單詞與它的替換。例如:

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

在你的清單,replace以上字典基礎上的話然後迭代,以獲得所需的列表:

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]'。它可以幫助OP知道你正在調用每個子列表的索引0,以及你爲什麼要這樣做。 –

+0

@BaconTech夠了。添加了評論的步驟 –