首先,您应该创建一个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 –
实际上,你没有一个字符串数组。使用你的用词不当(它应该是“列表”,而不是“数组”),你有一个字符串数组的数组。是否有任何理由为每个字符串附加额外的'['和']'? –