2015-05-04 55 views
0

分割字符串我有一個IP的範圍192.0.0.2-4爲字符串,並希望它在兩個新的字符串Python的初學者在兩個字符串

ip_start = '192.0.0.2' 
ip_end = '192.0.0.4' 

,所以我必須在"192.0.0.2-4"和分割搜索"-"有,但如何分割我可以做第二個字符串嗎?

+0

你可以張貼要拆分字符串? –

+1

@JulienSpronck:它在第一句話。 –

+1

範圍始終限制爲地址的最後一個字節? –

回答

4

如果範圍總是有限的地址的最後一個字節(八位),各執地址的最後一個點,並與您的最終值改爲:

ip_start, _, end_value = iprange.partition('-') 
first_three = ip_start.rpartition('.')[0] 
ip_end = '{}.{}'.format(first_three, end_value) 

我用str.partition()str.rpartition()這裏因爲你只需要拆分一次;對於這種情況,這些方法稍微快一點。方法總是返回3個字符串;分區字符串之前的所有內容,分區字符串本身以及之後的所有內容。由於我們只需要.分區的第一個字符串,因此我使用索引來選擇它作爲分配。由於您不需要保留那個短劃線或圓點,我將它們分配給一個名爲_的變量;因爲您不需要保留那個短劃線或圓點,所以我將它們分配給名爲_的變量;這只是一個慣例,用來表示你會完全忽略這個值。

演示:

>>> iprange = '192.0.0.2-4' 
>>> iprange.partition('-') 
('192.0.0.2', '-', '4') 
>>> iprange.partition('-')[0].rpartition('.') 
('192.0.0', '.', '2') 
>>> ip_start, _, end_value = iprange.partition('-') 
>>> first_three = ip_start.rpartition('.')[0] 
>>> ip_end = '{}.{}'.format(first_three, end_value) 
>>> ip_start 
'192.0.0.2' 
>>> ip_end 
'192.0.0.4' 

爲了完整起見:您還可以使用str.rsplit() method從右側分割字符串,但您需要在這種情況下,有限制:

>>> first.rsplit('.', 1) 
['192.0.0', '2'] 

這裏第二個參數1將分割限制爲找到的第一個.點。

+0

謝謝:)這正是我想要的! – Loretta

1

您可以通過使用「第一個」IP地址中的部分來建立第二個字符串。

>>> def getIPsFromClassCRange(ip_range): 
...  # first split up the string like you did 
...  tmp = ip_range.split("-") 
...  # get the fix part of the IP address 
...  classC = tmp[0].rsplit(".", 1)[0] 
...  # append the ending IP address 
...  tmp[1] = "%s.%s" % (classC, tmp[1]) 
...  # return start and end ip as a useful tuple 
...  return (tmp[0], tmp[1]) 
... 
>>> getIPsFromClassCRange("192.0.0.2-4") 
('192.0.0.2', '192.0.0.4') 
0

下面是3個步驟的解決方案,使用 一個generator expression

def ip_bounds(ip_string): 
    """Splits ip address range like '192.0.0.2-4' 
    into two ip addresses : '192.0.0.2','192.0.0.4'""" 

    # split ip address with last '.' 
    ip_head, ip_tail = ip_string.rsplit('.', 1) 

    # split last part with '-' 
    ip_values = ip_tail.split('-') 

    # create an ip address for each value 
    return tuple('{}.{}'.format(ip_head,i) for i in ip_values) 

ip_start, ip_end = ip_bounds('192.0.0.2-4') 
assert ip_start == '192.0.0.2' 
assert ip_end == '192.0.0.4' 
+0

請爲您的答案添加一些解釋,以便我們更好地瞭解它的功能和工作原理。 – Jon