0

I am reading from a file that looks like this: Ikard Wynne Llp|[('209.163.183.92', '209.163.183.95')]

    Innovation Technologies Ltd|[('91.238.88.0', '91.238.91.255'), ('195.128.153.0', '195.128.153.255')]
    House Of Flowers|[('69.15.170.220', '69.15.170.223'), ('108.178.223.20', '108.178.223.23')]
    Hertitage Peak Charter School|[('66.81.93.192', '66.81.93.207')]

and I am willing to convert the part after '|' to a list and then read the tuples from the list. I am using this script to do that but I the script recognize each list as an element instead of each tuple. Does any body know how to fix that?

for line in g:
    org= line.split("|")[0]
    ranges = [line.split('|')[1]]
    for range in ranges:
    print (range)

output:

[('91.238.88.0', '91.238.91.255'), ('195.128.153.0', '195.128.153.255')]
[('69.15.170.220', '69.15.170.223'), ('108.178.223.20', '108.178.223.23')]
[('66.81.93.192', '66.81.93.207')]

        for ip in range:
        print (ip)

output:

[
(
'
9
1
.
1
9
5
.
1
7
2
.
0
'
,
UserYmY
  • 8,034
  • 17
  • 57
  • 71

1 Answers1

3

Use literal_eval from the ast module:

>>> import ast
>>> s = "Innovation Technologies Ltd|[('91.238.88.0', '91.238.91.255'), ('195.128.153.0', '195.128.153.255')]"
>>> z = ast.literal_eval(s.split('|')[1])
>>> z
[('91.238.88.0', '91.238.91.255'), ('195.128.153.0', '195.128.153.255')]
>>> z[0]
('91.238.88.0', '91.238.91.255')
>>> z[0][1]
'91.238.91.255'
>>> type(z)
<type 'list'>
>>> type(z[0])
<type 'tuple'>

From the documentation:

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284