如何根据条件更新列表中的字符串 [英] How to update strings in a list based on condition

查看:80
本文介绍了如何根据条件更新列表中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我陷入了一个列表,想将子网/21更改为/24的情况.

I am stuck in a situation where I have a list and I want to change subnet /21 to /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.

Now it's printing right values but how I can change the values of a[-2:] 21 to 24 I fail to understand.

输出:

192.168.8.1/21
carry on
carry on

推荐答案

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

You cannot change a part of a string as strings are immutable. But you can replace the string with a corrected version.

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现在是什么:

And if you check what x is now:

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

这篇关于如何根据条件更新列表中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆