【问题标题】:How to update strings in a list based on condition如何根据条件更新列表中的字符串
【发布时间】:2017-08-06 08:47:14
【问题描述】:

我遇到了一种情况,我有一个列表,我想将子网 /21 更改为 /24

x = ['192.168.8.1/21', '192.168.4.36/24', '192.168.47.54/16']
for a in x:
    if "21" in (a[-2:]):
        print(a)
    else:
        print("carry on")

现在它正在打印正确的值,但我无法理解如何将 a[-2:] 21 的值更改为 24

输出:

192.168.8.1/21
carry on
carry on

【问题讨论】:

    标签: python string list replace


    【解决方案1】:

    您不能更改字符串的一部分,因为字符串是不可变的。但是您可以用更正的版本替换字符串。

    x = ['192.168.8.1/21', '192.168.4.36/24', '192.168.47.54/16']
    
    # we use enumerate to keep track of where we are in the list
    # where i is just a number
    for i, a in enumerate(x):
        # we can use a string method to check the ending
        if a.endswith('/21'):
            print('Replacing "/21" in "{}" with "/24"'.format(a))
            # here we actually update the list with a new string
            x[i] = a.replace('/21', '/24')
        else:
            print("carry on")
    
    #output:
    Replacing "/21" in "192.168.8.1/21" with "/24"
    carry on
    carry on
    

    如果您检查 x 现在是什么:

    x
    #output:
    ['192.168.8.1/24', '192.168.4.36/24', '192.168.47.54/16']
    

    【讨论】:

    • 如果您确定 /21 模式仅出现在您期望的位置(即:在字符串的末尾),则可以执行 for i, a in enumerate(x): x[i] = a.replace('/21', '/24')
    • 我想保留原始问题中的 print 语句。
    【解决方案2】:

    您可以使用列表推导和 if 语句有条件地更改列表中字符串的最后两个字符:

    x = [a[:-2] + '24' if a[-2:] == '21' else a for a in x]
    
    print x   # ['192.168.8.1/24', '192.168.4.36/24', '192.168.47.54/16']
    

    【讨论】:

      【解决方案3】:

      简单的答案是:

      print(a[:-2] + '24')
      

      这样会更灵活一点:

      r = {
          '21': '24',
          # '16': '17'
      }
      x = ['192.168.8.1/21', '192.168.4.36/24', '192.168.47.54/16']
      for a in x:
          s = a[-2:]
          if s in r:
              # get replacement
              n = a[:-2] + r[s]
              print(n)
          else:
              print("carry on")
      

      【讨论】:

        【解决方案4】:

        我会写一个这样的函数:

        def change_subnet(ips, from, to):
            for ip in ips:
                if ip[-2] == from:
                    yield ip[:-2] + to
                else:
                    yield ip
        

        你可以这样使用:

        >>> ips = ['192.168.8.1/21', '192.168.4.36/24', '192.168.47.54/16']
        >>> list(change_subnet(ips, "21", "24"))
        

        【讨论】:

          【解决方案5】:

          我们的想法是从a复制您感兴趣的部分,然后与您想要的结尾连接:

          x = ['192.168.8.1/21', '192.168.4.36/24', '192.168.47.54/16']
          for a in x:
            if "21" in (a[-2:]):
              print(a)
              a = a[:-2] + '24'
              print(a)
            else:
              print("carry on")
          

          【讨论】:

            猜你喜欢
            • 2011-07-01
            • 1970-01-01
            • 2021-12-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-05-03
            • 2023-04-05
            相关资源
            最近更新 更多