Python 用新词替换字符串中的字符

Python 用新词替换字符串中的字符,python,string,python-2.7,Python,String,Python 2.7,我有一个字符串数组,希望进行一些替换。例如: 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'], ['he

我有一个字符串数组,希望进行一些替换。例如:

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']]
my_replacement_dict = {
    "/": "and", 
    "&": "",   # Empty string to remove the word
    "\90": "", 
    "\"": ""
}
如果数组中的字符串包含这些字符,如何将/and替换为and、删除(&and)和\90以及删除周围的单词?

如该帖子所示:

例如,你可以使用类似的东西

if "/" in my_string:
    new_string = my_string.replace("/", "and")

并将其包含在整个数组的循环中。

首先,您应该创建一个dict对象,用它的替换项映射单词。例如:

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']]
my_replacement_dict = {
    "/": "and", 
    "&": "",   # Empty string to remove the word
    "\90": "", 
    "\"": ""
}
然后,根据上面的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` 
新清单的最终内容为:


看看官方文档中的replace方法:实际上,您没有字符串数组。使用错误的名称,它应该是列表,而不是数组,您有一个字符串数组数组。每个字符串周围都有额外的[and]吗?从OPs问题来看,它们可能是python的新手。你能在你的代码中解释得更详细一点吗。例如,请解释调用sub_list[0]的原因。知道您正在调用每个子列表的索引0以及为什么这样做可能会有帮助。@BaconTech很公平。将步骤添加为注释