在python中的url中使用变量

use*_*975 6 python

对不起这个非常基本的问题.我是Python的新手,并试图编写一个可以打印URL链接的脚本.IP地址存储在名为list.txt的文件中.我该如何在链接中使用变量?能否请你帮忙?

# cat list.txt

192.168.0.1
192.168.0.2
192.168.0.9
Run Code Online (Sandbox Code Playgroud)

脚本:

import sys
import os

file = open('/home/list.txt', 'r')

for line in file.readlines():
    source = line.strip('\n')
    print source

link = "https://(source)/result”
print link
Run Code Online (Sandbox Code Playgroud)

输出:

192.168.0.1
192.168.0.2
192.168.0.9
https://(source)/result
Run Code Online (Sandbox Code Playgroud)

预期产量:

192.168.0.1
192.168.0.2
192.168.0.9
https://192.168.0.1/result
https://192.168.0.2/result
https://192.168.0.9/result
Run Code Online (Sandbox Code Playgroud)

Pad*_*ham 6

您需要传递实际变量,您可以遍历文件对象,这样您就不需要使用readlines并使用它with来打开文件,因为它会自动关闭它们.如果要查看每一行,还需要在循环内部打印,并str.rstrip()从每行末尾删除任何换行符:

with open('/home/list.txt') as f:  
    for ip in f:
        print "https://{0}/result".format(ip.rstrip())
Run Code Online (Sandbox Code Playgroud)

如果要存储所有链接,请使用列表解析:

with  open('/home/list.txt' as f:
    links = ["https://{0}/result".format(ip.rstrip()) for line in f]
Run Code Online (Sandbox Code Playgroud)

对于python 2.6,您必须传递位置参数数字索引,{0}使用str.format.

您还可以使用名称传递给str.format:

with open('/home/list.txt') as f:
    for ip in f:
        print "https://{ip}/result".format(ip=ip.rstrip())
Run Code Online (Sandbox Code Playgroud)


sat*_*oru 2

尝试这个:

lines = [line.strip('\n') for line in file]

for source in lines:
    print source

for source in lines:
    link = "https://{}/result".format(source)
    print link
Run Code Online (Sandbox Code Playgroud)

您刚才描述的功能通常称为字符串插值。在 Python 中,这称为字符串格式化

Python 中的字符串格式化有两种风格:旧风格和新风格。我在上面的示例中展示的是新样式,其中我们使用名为 的字符串方法进行格式化format。而旧样式使用%运算符,例如。"https://%s/result" % source