[英]python regexp remove last numbers from string
How can I remove the last digits from a string using python regexp or similar: I have an IP-address 10.121.100.200
and would want to only display 10.121.100.
如何使用python regexp或类似方法从字符串中删除最后一位数字:我有一个IP地址
10.121.100.200
,并且只想显示10.121.100.
leaving out the last numbers. 遗漏了最后的数字。
Regex: 正则表达式:
re.sub(r'\d+$', '', ip)
Without regexes 没有正则表达式
''.join(ip.rpartition('.')[:2])
>>> v = '10.121.100.200'
>>> ".".join(v.split('.')[0:-1])
'10.121.100'
If you want to leave the last little dot at the end, then: 如果你想在最后留下最后一个小点,那么:
>>> ".".join(v.split('.')[0:-1]) + '.'
'10.121.100.'
Just refactor it to a function, and you're good to go. 只需将它重构为一个函数,你就可以了。
Another version 另一个版本
'{}.'.format('10.121.100.200'.rsplit('.', 1)[0])
'10.121.100.'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.