[Tutor] Req Assistance with 1st Project.
Peter Otten
__peter__ at web.de
Sun May 31 10:57:26 CEST 2015
Nym City via Tutor wrote:
> Hello all,
> I am working on my first Python project and I need some help. Here is what
> my project is about. I want to be able to read in from a text file that
> contains a list of IP addresses (maybe even hostnames) and write out each
> IP in the list in the following format: "172.0.0.1" OR "10.10.10.10" OR
> ...... After some online search, It seems like I would want to create a
> list (which I did) however, the challenge is that I can't figure out how
> to add the double quotes and OR after each entry in my list.
>
> Here is my current code (also attached):
> f = open("BadIPList", "r+")
> IOCs = []
> for line in f:
> line = line.strip()
> IOCs.append(line)
> print(IOCs)
> f.close()
> Thank you in advance.
Python has clever ways to achieve this, but you should first do it the hard
way:
- Just like you remove the whitespace from the line you can add something,
e. g. line = line + "!" will add an exclamation mark. In a similar way you
can add '"' before and after the line string.
- Instead of printing the whole list you can loop over the items:
for ioc in IOCs:
print("OR", ioc, end=" ")
print()
This will print the "OR" followed by an IP. There's one problem though,
there's an OR before the first IP. Can you avoid that with a flag (a
variable that is either True or False) and
... # init flag
for ioc in IOCs:
if ...: # check flag
... # update flag
else:
print("OR", end=" ")
print(ioc, end=" ")
OK, now for the clever way:
with open("BadIPList") as f:
print(" OR ".join('"{}"'.format(line.strip()) for line in f))
That may be concise, but is also a bit messy. To make it more readable you
can break it apart:
with open("BadIPList") as f:
ips = (line.strip() for line in f)
quoted_ips = ('"{}"'.format(ip) for ip in ips)
print(" OR ".join(quoted_ips))
The (... for ... in ...) is called "generator expression", a kind of
sequence that that lazily delivers items.
More information about the Tutor
mailing list