Using variable in url in python

Sorry for this very simple question. I am new to Python and am trying to write a script that can print URL links. IP addresses are stored in a file called list.txt. How to use a variable in a link? Could you help me?

# cat list.txt 192.168.0.1 192.168.0.2 192.168.0.9 

script:

 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 

output:

 192.168.0.1 192.168.0.2 192.168.0.9 https://(source)/result 

Expected Result:

 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 
+6
source share
5 answers

You need to pass a valid variable, you can iterate over the file, so you do not need to use readlines and use with to open your files, since they automatically close them. You also need to print inside the loop if you want to see each line, and str.rstrip() removes the lines from the end of each line:

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

If you want to keep all links, use the list :

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

For python 2.6 you need to pass the numerical index of the positional argument, i.e. {0} using str.format .

You can also use names to go to str.format:

 with open('/home/list.txt') as f: for ip in f: print "https://{ip}/result".format(ip=ip.rstrip()) 
+6
source

Try the following:

 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 

You just described the often called line interpolation . In Python, this is called string formatting .

Python has two styles for formatting strings: the old style and the new style. What I showed in the above example is a new style in which we format a string method called format . While the old style uses the % operator, for example. "https://%s/result" % source

+2
source

Get the link inside the loop, you do not add data to it, you assign it every time. Use something like this:

 file = open('/home/list.txt', 'r') for line in file.readlines(): source = line.strip('\n') print source link = "https://%s/result" %(source) print link 
+2
source

Use the formatting specifier for the string, and also put the section for printing links in a for loop something like this:

 import sys import os file = open('/home/list.txt', 'r') for line in file.readlines(): source = line.strip('\n') print source link = "https://%s/result"%source print link 
+2
source
 import sys import os file = open('/home/list.txt', 'r') for line in file.readlines(): source = line.strip('\n') print source link = "https://" + str(source) + "/result" print link 
+1
source

Source: https://habr.com/ru/post/988078/


All Articles