2017-04-13 124 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够了。添加了评论的步骤 –