Ahsan Naseem
Ahsan Naseem

Reputation: 1106

How to update strings in a list based on condition

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

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

Output:

192.168.8.1/21
carry on
carry on

Upvotes: 0

Views: 1372

Answers (5)

JejeBelfort
JejeBelfort

Reputation: 1663

The idea would be to copy the part you are interested in from a, and then concatenate with the end you want :

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

Upvotes: 0

Graipher
Graipher

Reputation: 7186

I would write a function like this:

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

which you can use like this:

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

Upvotes: 0

wolfmanx
wolfmanx

Reputation: 481

The simple answer is:

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

A little bit more flexible would be this:

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

Upvotes: 0

James
James

Reputation: 36598

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

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

Upvotes: 4

Nils Werner
Nils Werner

Reputation: 36739

You can conditionally change the last two characters of a string in a list using a list comprehension and an if statement:

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

Upvotes: 2

Related Questions