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

时间:2017-04-13 14:19:07

标签: 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'], ['hello world']]

如何更换/更换,删除&和\ 90,并删除""如果数组中的字符串包含这些字符?

2 个答案:

答案 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']]

答案 1 :(得分:0)

如该帖子所示:How to delete a character from a string using python?

您可以使用例如

之类的东西
if "/" in my_string:
    new_string = my_string.replace("/", "and")

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