删除字符串中第 4 个句点后的所有内容
Delete everything after 4th period in string
我试图在 python 2.7 中操作 tcpdump 的输出。我想要做的是删除IP地址的端口部分。
例如,如果输入字符串是
192.168.0.50.XXXX
我将如何着手 删除 第 4 期之后的所有内容,以便 output 会是
192.168.0.50
我考虑过对字符串的 长度 做一些事情,唯一的问题是端口长度在我的示例中可以是 1-5 位数字 (0-9999) .
我唯一能想到的就是用句号做一些事情作为一个 普通 IP 只包含 3 和一个 IP附加 端口 有 4.
试试这个
print('.'.join("192.168.0.50.XXXX".split('.')[:-1])) #or [:4], depending on what you want. To just remove the port, the -1 should work.
使用句点作为分隔符将字符串分成几组。取前四组重新拼在一起,使用相同的句点作为分隔符:
ip = "192.168.0.50.XXXX"
".".join(ip.split(".")[:4])
#'192.168.0.50'
使用rsplit()
最干净或最简单的路线:
s = "192.168.0.50.XXXX"
s = s.rsplit('.',1)[0]
输出:
192.168.0.50
Returns a list of strings after breaking the given string from right
side by the specified separator.
我已经使用 split 和 join 函数来执行此操作。
这是一步一步的过程:
ip="192.168.0.50.XXXX"
拆分一个字符串,并使用定义的分隔符将数据添加到一个字符串数组。
sp=ip.split(".")
#['192', '168', '0', '50', 'XXXX']
到 select 数组中的所有内容 除了 last 项
sp=sp[:-1]
#['192', '168', '0', '50']
然后使用 join 函数连接这些元素:
".".join(sp)
#'192.168.0.50'
我试图在 python 2.7 中操作 tcpdump 的输出。我想要做的是删除IP地址的端口部分。
例如,如果输入字符串是
192.168.0.50.XXXX
我将如何着手 删除 第 4 期之后的所有内容,以便 output 会是
192.168.0.50
我考虑过对字符串的 长度 做一些事情,唯一的问题是端口长度在我的示例中可以是 1-5 位数字 (0-9999) .
我唯一能想到的就是用句号做一些事情作为一个 普通 IP 只包含 3 和一个 IP附加 端口 有 4.
试试这个
print('.'.join("192.168.0.50.XXXX".split('.')[:-1])) #or [:4], depending on what you want. To just remove the port, the -1 should work.
使用句点作为分隔符将字符串分成几组。取前四组重新拼在一起,使用相同的句点作为分隔符:
ip = "192.168.0.50.XXXX"
".".join(ip.split(".")[:4])
#'192.168.0.50'
使用rsplit()
最干净或最简单的路线:
s = "192.168.0.50.XXXX"
s = s.rsplit('.',1)[0]
输出:
192.168.0.50
Returns a list of strings after breaking the given string from right side by the specified separator.
我已经使用 split 和 join 函数来执行此操作。
这是一步一步的过程:
ip="192.168.0.50.XXXX"
拆分一个字符串,并使用定义的分隔符将数据添加到一个字符串数组。
sp=ip.split(".")
#['192', '168', '0', '50', 'XXXX']
到 select 数组中的所有内容 除了 last 项
sp=sp[:-1]
#['192', '168', '0', '50']
然后使用 join 函数连接这些元素:
".".join(sp)
#'192.168.0.50'