首先,您應該創建一個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']]
HTTPS ://www.tutorialspoint.com/python/string_replace.htm – oshaiken
查看官方文檔中的替換方法:https://docs.python.org/2/library/string.html –
實際上,你沒有一個字符串數組。使用你的用詞不當(它應該是「列表」,而不是「數組」),你有一個字符串數組的數組。是否有任何理由爲每個字符串附加額外的'['和']'? –