Reputation: 21
for i in range(len(npa)):
filename = '/lca_rcdist.php?npa1=503&nxx1=745&npa2=503&nxx2=' + npa[i]
reply = urllib.request.urlopen(servername + filename)
if reply.status != 200:
print('Error sending request', reply.status, reply.reason)
else:
data = reply.readlines()
reply.close()
for line in data[:showlines]:
cLine = line.decode('utf-8')
if '"ofrom">N<' in cLine:
print('NXX ,' + npa[i])
The following output is NXX,269NXX,298NXX,300NXX
and so on, is there a way to add if and else statement so that the output does not contain a comma and NXX in front of the first entry? example: 269NXX, 298NXX
? I'm new to this and still strugling with if and else statements on scripts like these. Any ifo on how to change the output using if, else statemnet will be appriciated.
Upvotes: 1
Views: 265
Reputation: 174624
for i in range(len(something))
this is an anti-pattern in Python. Correcting your code for this, and a few other things:
results = []
for i in npa:
qs = urllib.urlencode({'npa': i})
filename = '/lca_rcdist.php?npa1=503&nxx1=745&npa2=503&{0}'.format(qs)
url = '{0}{1}'.format(servername,filename)
reply = urllib.request.urlopen(url)
if reply.status != 200:
print('Error sending request: {0.status} {0.reason}'.format(reply))
else:
data = reply.readlines()
reply.close()
for line in data[:showlines]:
cLine = line.decode('utf-8')
if '"ofrom">N<' in cLine:
results.append('NXX{0}'.format(i))
Upvotes: 0
Reputation: 21
I dont know python but you can try this
declare a variable before the loop and set the value to 0 and then if the value of the variable is 0 in first if condition print without NXX and change the value of variable to 1 and put the else code with NXX. Hope this helps.
flagfirst=0
for line in data[:showlines]:
cLine = line.decode('utf-8')
if '"ofrom">N<' in cLine:
if flagfirst==0:
print(npa[i])
flagfirst=1
else:
print('NXX ,' + npa[i])
Upvotes: 2
Reputation: 3913
I know this is a bit too complex than what you asked, but this is how I'd do it (I'm not saying it's the correct way -- I'm not sure actually).
I'd change the entire last for loop from this:
for line in data[:showlines]:
cLine = line.decode('utf-8')
if '"ofrom">N<' in cLine:
print('NXX ,' + npa[i])
To this:
'NXX,'.join([npa[i] for l in data[:showlines] if '"ofrom">N<' in l.decode('utf-8')])
Upvotes: 1
Reputation: 168626
Create a list and then use str.join()
:
result = [] # NEW
for i in range(len(npa)):
... # blah, blah, same as your example, until
if '"ofrom">N<' in cLine:
result.append(npa[i]) # CHANGED
print (','.join(result)) #NEW
Upvotes: 5