简体   繁体   中英

python string manipulation to match windows firewall syntax

I have a string like so:

string = "27.116.56.0 27.116.59.255 43.230.209.0 43.230.209.255"  #(white space sep)

how would you go from it to this format:

string = "27.116.56.0-27.116.59.255,43.230.209.0-43.230.209.255"

**the string will have unknown length , the elements number will allways be even.

I've looked at some close examples and got confused.. what is the best easy way doing that?

# Create a new list containing the ips
str_elems = "27.116.56.0 27.116.59.255 43.230.209.0 43.230.209.255".split()
# Use a format string to build the new representation, where each list element is assigned a spot in the string
# We use the * operator to convert the single list into multiple arguments for the format
new_str = ("{}-{},"*(len(str_elems)/2)).format(*str_elems).rstrip(',')

For a general solution, you can iterate over your split string in chunks of 2.

s = "27.116.56.0 27.116.59.255 43.230.209.0 43.230.209.255".split()
print(",".join(["-".join(s[i:i + 2]) for i in range(0, len(s), 2)]))
#'27.116.56.0-27.116.59.255,43.230.209.0-43.230.209.255'

Join the inner chunks with a "-" and finally join the whole thing with ","

Something as simple as this?

what_you_have = "27.116.56.0 27.116.59.255 43.230.209.0 43.230.209.255"

what_you_want = "27.116.56.0-27.116.59.255,43.230.209.0-43.230.209.255"

splt = what_you_have.split()

what_you_have_transformed = splt[0] + "-" + splt[1] + "," + splt[2] + "-" + splt[3]

print(what_you_want==what_you_have_transformed) # prints True

Or it can have more addresses?

string = "27.116.56.0 27.116.59.255 43.230.209.0 43.230.209.255"

ip_list = string.split(" ")                     # split the string to a list using space seperator

for i in range(len(ip_list)):                   # len(ip_list) returns the number of items in the list (4)
                                                # range(4) resolved to 0, 1, 2, 3 

    if (i % 2 == 0): ip_list[i] += "-"          # if i is even number - concatenate hyphen to the current IP string 
    else: ip_list[i] += ","                     # otherwize concatenate comma

print("".join(ip_list)[:-1])                    # "".join(ip_list) - join the list back to a string
                                                # [:-1] trims the last character of the result (the extra comma)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM