Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.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 3.x 尝试删除空格或制表符后面右侧的所有字符_Python 3.x - Fatal编程技术网

Python 3.x 尝试删除空格或制表符后面右侧的所有字符

Python 3.x 尝试删除空格或制表符后面右侧的所有字符,python-3.x,Python 3.x,我正在运行一个从互联网下载文本的代码 我正在寻找一种只保留IP地址并将其保存到文件的简单方法 无论我怎样试着剥去每条线的正确部分,它都不起作用。我认为响应中的空格是一个标签,但即使我尝试了,它也没有起到任何作用 我用不同的组合尝试了strip和rstrip,但运气不佳 导入请求 响应=请求。获取(“https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt") 打印(response.text.rstrip(“”)) 我只

我正在运行一个从互联网下载文本的代码

我正在寻找一种只保留IP地址并将其保存到文件的简单方法

无论我怎样试着剥去每条线的正确部分,它都不起作用。我认为响应中的空格是一个标签,但即使我尝试了,它也没有起到任何作用

我用不同的组合尝试了
strip
rstrip
,但运气不佳

导入请求
响应=请求。获取(“https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt")
打印(response.text.rstrip(“”))
我只希望一行一行地看到IP地址,如下所示:

171.25.193.25 

89.234.157.254

171.25.193.77
但是,输出看起来是这样的:

171.25.193.25   14

89.234.157.254  12

171.25.193.77   12

171.25.193.235  12

171.25.193.20   12

您可以使用
split
功能

没有参数的
str.split()
方法在空格上拆分:


请尝试打印(response.text.split()[0])

由于您的整个请求被视为一个字符串,因此拆分将无法正常工作。因此,您必须将请求逐行分割,并对每行进行分割,例如

import requests
response = requests.get("https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt")
lines = response.text.split('\n')[4:] # ignore 4 lines.
for line in lines:
    print(line.split()[0])
这将为您提供如下结果

171.25.193.25
89.234.157.254
171.25.193.77
...

这就是我建议的解决方案。

谢谢,这正是我想要的。唯一的问题是最后一次打印超出了索引打印范围(line.split()[0])索引器:列表索引超出范围我将在返回主页时检查:),但您可以尝试使用此
lines=response.text.split('\n')[4:-1]
.Perfect。这就解决了问题。非常感谢。
import requests
response = requests.get("https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt")
response = response.text.split()
response = "\n".join([x for x in response if '.' in x])
print(response)