Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python字符串操作以匹配windows防火墙语法_Python_String - Fatal编程技术网

python字符串操作以匹配windows防火墙语法

python字符串操作以匹配windows防火墙语法,python,string,Python,String,我有这样一个字符串: string = "27.116.56.0 27.116.59.255 43.230.209.0 43.230.209.255" #(white space sep) 您将如何从它转换为这种格式: string = "27.116.56.0-27.116.59.255,43.230.209.0-43.230.209.255" **字符串长度未知,元素数始终为偶数 我看了一些相近的例子,感到困惑。。 做这件事最简单的方法是什么?像这样简单的事情 # Create a n

我有这样一个字符串:

string = "27.116.56.0 27.116.59.255 43.230.209.0 43.230.209.255"  #(white space sep)
您将如何从它转换为这种格式:

string = "27.116.56.0-27.116.59.255,43.230.209.0-43.230.209.255"

**字符串长度未知,元素数始终为偶数

我看了一些相近的例子,感到困惑。。
做这件事最简单的方法是什么?

像这样简单的事情

# 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(',')
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

或者它可以有更多的地址?

对于一般解决方案,您可以选择2个地址


用一个
“-”
连接内部块,最后用
连接整个块,“

不要给变量命名
字符串,因为它会踩在
字符串
模块上所有字符串都是这样的吗?共有3段?字符串长度未知,元素数为偶数。@字符串长度未知,元素数始终为偶数。@Avarage_joe我已将其更新为支持未知长度。**字符串长度未知,元素数始终为偶数。
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'
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)