如何更改python列表中字符串的最后2个元素?

时间:2017-03-15 14:31:49

标签: python string list replace

嘿大家我陷入困境,我有一个列表,我想将子网/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

5 个答案:

答案 0 :(得分:4)

由于字符串是不可变的,因此无法更改字符串的一部分。但您可以使用更正的版本替换字符串。

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

答案 1 :(得分:2)

您可以使用list comprehension和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']

答案 2 :(得分:0)

简单的答案是:

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")

答案 3 :(得分:0)

我会写一个这样的函数:

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"))

答案 4 :(得分:0)

这个想法是从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")