我如何从最后一个“。”之后的字符串中删除最后一个字符?

How do i remove the last character from a string after the last "."

我正在编写一个 python 脚本,该脚本获取 Ip 并计算广播,该广播仅删除最后一个“。”之后的 ip 的最后摘要。并将它们替换为 255

input = "192.168.0.100" 
input = #string operation
print(input)
input = "192.168.0.100" 
loc = input.rfind('.')
inputShort = input[1:loc]
print(loc)
print(inputShort)

rfind 查找“.”的最后一次出现。字符和 inputShort 然后是所有字符,但不包括最后一个“.”。

>>> input = "192.168.0.100"
>>> from re import sub
>>> sub('(.[01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-4])$', '.255', input)
'192.168.5.255'

广播地址并不总是像上一个摘要那样只是 255。仅当前缀 len 为 /24(或掩码为 255.255.255.0)时才会如此。