我有一个字符串数组,并希望进行一些替换。例如:
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,并删除""如果数组中的字符串包含这些字符?
答案 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")
将它包含在整个数组的循环中。