开发者

Python: Printing a list without the brackets and single quotes?

I have a list full of IP addresses. I would like to iterate through the list and print each IP address. When I try doing this:

def printList(theList):
    for item in theList:
        print item

And the output looks like this:

开发者_运维知识库
['8.0.226.5']
['8.0.247.5']
['8.0.247.71']
['8.0.249.28']
['8.0.249.29']

I have tried everything, including "print item[0]" in the loop. What am I doing wrong?


Each item in the list is itself a singleton list. There's propably no reason for this - if you can't name one, go and remove them (by using re.find over re.findall or returning a single item from the list returned by re.findall), they're just redundant and cause trouble like in this case.

Regardless, print item[0] should work as it's printing the single element in the list, and unlike the str() of lists, it won't run the item through repr first (which causes the quotes and would escape unprintable characters if there were any in the string). And once you got rid of the redundant singleton lists, print '\n'.join(items) will work as well.

Your code throws an error if there is an empty list in theList. If there is a line in recentFile that does not contain anything formatted like an IP, an empty list will be returned by returnIP, and if any line in comparisonFile (by the way: you open it with a descriptive name at the beginning, but open it again and again without a descriptive name in chechMatch) contains no IP address either, you'll get another empty list which of course equals the empty list passed as parameter ip. So for non-IP names in recentFile, empty lists will be added. This whole troubel can be avoided if you return strings instead of singleton lists from returnIP, use None when there is no IP in the current line, and skip the checking/appending in compareFiles if returnIP returns None.


I think theList is not a list of IPs but a list of lists of IPs(each of them with 1 element).

Another cause of the problem would be that you have an IP class with an overwritten str method that prints it like that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜