如何根据条件更新列表中的字符串

2024-03-13

我陷入这样的情况:我有一个列表,但我想更改子网/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 to 24我不明白。

Output:

192.168.8.1/21
carry on
carry on

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

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 is now:

x
#output:
['192.168.8.1/24', '192.168.4.36/24', '192.168.47.54/16']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何根据条件更新列表中的字符串 的相关文章

随机推荐