【问题标题】:How do i remove the last character from a string after the last "."如何从最后一个“。”之后的字符串中删除最后一个字符
【发布时间】:2020-03-12 15:26:57
【问题描述】:

我正在研究一个 python scipt,它获取和 Ip 并计算 brodcast,它只是在最后一个“。”之后删除 ip 的最后一个摘要。并将它们替换为 255

input = "192.168.0.100" 
input = #string operation
print(input)

【问题讨论】:

  • "str.split" 或 str.rfind" 可以帮助你。

标签: python string ip


【解决方案1】:
input = "192.168.0.100" 
loc = input.rfind('.')
inputShort = input[1:loc]
print(loc)
print(inputShort)

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

【讨论】:

    【解决方案2】:

    广播地址并不总是只有 255 作为最后一个摘要。仅当前缀 len 为 /24(或 mask 为 255.255.255.0)时才会如此。

    【讨论】:

      【解决方案3】:
      >>> 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'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-19
        • 2021-12-11
        • 2011-11-18
        • 1970-01-01
        • 2013-09-12
        相关资源
        最近更新 更多