Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字符串中拉出字符串(拆分?)_Python - Fatal编程技术网

Python 从字符串中拉出字符串(拆分?)

Python 从字符串中拉出字符串(拆分?),python,Python,我有一个字符串-示例如下: g0/1 192.168.1.1 YES NVRAM up up 我想从中提取IP地址,但不是最后一个八位组。我想拉192.168.1。这样以后就可以使用了 我认为我需要使用split,但不确定如何实现这一点 output = ' g0/1 192.168.1.1 YES NVRAM up up'

我有一个字符串-示例如下:

g0/1                  192.168.1.1     YES NVRAM  up                    up
我想从中提取IP地址,但不是最后一个八位组。我想拉192.168.1。这样以后就可以使用了

我认为我需要使用split,但不确定如何实现这一点

output = '    g0/1                  192.168.1.1     YES NVRAM  up                    up'
ouput = ouput.split('192.168.1.',)
你可以用

编辑:从
match()
更改为
search()
,因为
match()
只查看字符串的开头

另外,假设您希望对多个字符串执行此操作,则可以使用函数,该函数将返回正则表达式的所有匹配组的列表

> import re

> input_string = "g0/1                  192.168.1.1     YES NVRAM  up                    up"
> outputs = re.search('\d{1,3}\.\d{1,3}\.\d{1,3}\.', input_string)
> print(outputs)
['192.168.1.']
只需使用
split()


我谦恭地说,正则表达式对于这项任务来说太沉重了。我似乎陷入了使用正则表达式的陷阱,即使在没有必要的时候。
> import re

> input_string = "g0/1                  192.168.1.1     YES NVRAM  up                    up"
> outputs = re.search('\d{1,3}\.\d{1,3}\.\d{1,3}\.', input_string)
> print(outputs)
['192.168.1.']
>>> output.split()[1].rsplit(".", 1)[0]
'192.168.1'