【问题标题】:replace characters in string with new word [duplicate]用新词替换字符串中的字符[重复]
【发布时间】:2017-04-13 14:19:07
【问题描述】:

我有一个字符串数组,并且想做一些替换。例如:

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

如果数组中的字符串包含这些字符,如何将 / 替换为 and,删除 & 和 \90,以及删除单词周围的 ""?

【问题讨论】:

标签: python string python-2.7


【解决方案1】:

首先,您应该创建一个dict 对象来映射单词及其替换。例如:

my_replacement_dict = {
    "/": "and", 
    "&": "",   # Empty string to remove the word
    "\90": "", 
    "\"": ""
}

然后根据上面的dict遍历你的列表和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']]

【讨论】:

  • 从 OP 的问题来看,他们可能是 python 新手。你能在你的代码中解释更多细节吗?例如解释你为什么打电话给sub_list[0]。它可能有助于 OP 知道您正在调用每个子列表的索引 0 以及您这样做的原因。
  • @BaconTech 够公平的。将步骤添加为 cmets
【解决方案2】:

正如在那篇帖子中看到的那样:How to delete a character from a string using python?

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-09
    • 2017-12-20
    • 2011-10-10
    • 2021-06-17
    • 2012-10-05
    • 1970-01-01
    相关资源
    最近更新 更多