Martin Lopez
Martin Lopez

Reputation: 103

Converting second element in a tuple to an integer

I am trying to get rid of the ' ' in the 2nd element of each tuple.

my code is

def read_records_from_file(filename):
    final_list = []
    infile=open(filename)
    lines=infile.readlines()
    i = 0
    while i < len(lines):
        element = lines[i]
        i += 1
        if element.strip() == '<begin step data>':
            break

    while i < len(lines):       
        element = lines[i]
        clean_element = element.rstrip("\n")
        list = clean_element.split(",")
        tuple1 = tuple(list)
        i += 1
        if element.strip() == '<end step data>':
            break         
        final_list.append(tuple1)
    return final_list

my code gives me

[('2001-01-01', '12776'), ('2001-01-02', '15128')]

but I need

[('2001-01-01', 12776), ('2001-01-02', 15128)]

I am not sure how to only change the 2nd element of each tuple to integer.

Note: I am not allowed to use for loops

Any help is much-appreciated Thanks!

Upvotes: 1

Views: 1273

Answers (1)

zimmerrol
zimmerrol

Reputation: 4951

You have to cast the second tuple entry to the int data type and not use a string representation (this gives you the quotation marks):

 list = clean_element.split(",")
 tuple1 = (list[0], int(list[1]))

Edit: Please move these lines to the beginning of your second while loop:

element = lines[i]
if element.strip() == '<end step data>':
    break   

to solve your second problem.

In the end, you get this code:

def read_records_from_file(filename):
    final_list = []
    infile=open(filename)
    lines=infile.readlines()

    for i in range(len(lines)):  
        element = lines[i]
        clean_element = element.rstrip("\n").strip()
        if clean_element == '<end step data>':
            break     

        list = clean_element.split(",")
        tuple1 = tuple(list)

        final_list.append(tuple1)
    return final_list

Upvotes: 2

Related Questions