#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    6
    Rep Power
    0

    Input from the file into program


    Hi there,

    Bit of a problem with manipulating numbers from the file.
    Code:
    n = linecache.getline('myfile.txt',1)
    b = linecache.getline('myfile.txt',2)
    w = linecache.getline('myfile.txt',3)
    print (n)
    print (b)
    print (w)
    The result of it is :
    4
    11 13 15 7
    1 2 10

    Now, I would like to add numbers from b separately into tuple so I can access them individually. Currently I can only get this:
    ('11 13 15 7\n',)
    But I need to have it in this format: (11 , 13 , 15 ,7)

    Any help please make your suggestions
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,897
    Rep Power
    481
    Your variable b from linecache is a tuple containing one item, a string. Access the string using tuple.__getitem__ as supported with python syntax b[0] , split the string using default white space, convert the fields to your desired data type (I've assumed int of your example) and finally form a tuple .



    b = ('11 13 15 7\n',)
    tuple_of_ints = tuple(int(B) for B in b[0].split())



    More suggestions:
    Now, I would like to add numbers from b separately into tuple
    Please find another verb that is not "add". "add" in a programming context first means arithmetic addition.
    "Create a tuple from the numbers in the string."

    Also, "add" meaning "insert" numbers into a tuple is impossible because tuples are immutable. Tuples can be created, accessed, destroyed. Tuples may not be otherwise altered.
    Last edited by b49P23TIvg; November 7th, 2013 at 09:33 AM.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    6
    Rep Power
    0
    thanks for correcting me that sorted an issue.

    Could you also tell me how would you convert variable n of class str to int or floating point number, so I could generate a tuple based on this number.
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,897
    Rep Power
    481

    Time to learn the builtins


    >>> print(dir(__builtins__))


    Now, get help for the names that sound promising, for instance

    >>> help(float)
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo