Search code examples
pythonpython-3.xsplititerable-unpacking

Python : Splitting a value into two and assigning into two different variable


I am trying to get a string from a file that has a start and end date range as below:

"Date Range = January 1, 2001 to December 24, 2008"

I have to pick this date range (January 1, 2001 to December 24, 2008) and split it and assign it into 2 different variables. I am able to fetch the date range and split them, but when assigning I get an error.

file_path = open("C:\\Users\\vinnu\\Desktop\\ARF_LS00006493_339313_Tremont.txt")
content = file_path.read()

#find and pick the date range
size = len(content)
start =0
while start < size:
    start = content.find("Date Range: ",start)
    start = start if start != -1 else size
    #fetch only till the end of line
    end = content.find("\n", start)
    end = end if end != -1 else size
    date_range = (content[start+12:end])
    start = end + 1
    #printing test
    print (date_range)

    #split
    date1,date2= date_range.split(' to ')
    print (date1)
    print (date2)

I get the below output with an error:

January 1, 2001 to December 24, 2008
January 1, 2001
December 24, 2008

Traceback (most recent call last):
  File "C:/Users/vinnu/Desktop/split_eg3.py", line 19, in <module>
    date1,date2= date_range.split(' to ')
ValueError: not enough values to unpack (expected 2, got 1)

Solution

  • I'll try to explain the output you are getting

    First time in the loop, all is good...

    January 1, 2001 to December 24, 2008
    January 1, 2001
    December 24, 2008
    

    Now you are entering the loop again (most likely you have some \n\n in the file at the end of it)

    start = content.find("Date Range: ",start)
    start = start if start != -1 else size
    

    start should "size" now

    date_range = (content[start+12:end]) # start==size remember? => ""
    start = end + 1
    #printing test
    print (date_range) #you print an empty string here!
    

    After printing the empty line

    date1,date2= date_range.split(' to ') #splitting the empty string
    

    and exploding:

    Traceback (most recent call last):
      File "C:/Users/vinnu/Desktop/split_eg3.py", line 19, in <module>
        date1,date2= date_range.split(' to ')
    ValueError: not enough values to unpack (expected 2, got 1)