#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2004
    Posts
    330
    Rep Power
    15

    Converting Long to String


    Hello,

    I am trying to write the output of a script which are "Long" objects, to a file.
    I use this command

    Code:
    output.write(Data)
    where Data is Long. I get an error that Data has to be string. Is there anyway to convert Long objects to string?

    Thanks
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2004
    Posts
    461
    Rep Power
    25
    you can use pickle or cPickle(both are the same except cPickle does it faster)

    Code:
    import cPickle
    longNum = 1030402043032L
    f = open("file", "w")
    cPickle.dump(longNum, f)
    f.close()
    or to read you can do:
    Code:
    import cPickle
    f = open("file","r")
    longNum = cPickle.load(f)
    f.close()
    print longNum

    you should look up pickle on pythons docs. it is a very powerfull tool.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2004
    Location
    Bimingham,AL
    Posts
    68
    Rep Power
    11
    i would do
    output.write(str(Data))
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    What wx_uab said. If x is a long value then str(x) will convert it to a string WITHOUT the 'L' on the end. If you want to keep the 'L' (e.g. to read it back into a Python program in the future) then you can use repr(x).

    Code:
    >>> x = 1L<<40
    >>> str(x)
    '1099511627776'
    >>> repr(x)
    '1099511627776L'
    Dave - The Developers' Coach
  8. #5
  9. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Originally Posted by DevCoach
    What wx_uab said. If x is a long value then str(x) will convert it to a string WITHOUT the 'L' on the end. If you want to keep the 'L' (e.g. to read it back into a Python program in the future) then you can use repr(x).

    Code:
    >>> x = 1L<<40
    >>> str(x)
    '1099511627776'
    >>> repr(x)
    '1099511627776L'
    Dave - The Developers' Coach
    You can also use back ticks as a shortcut for the repr() function call i.e.

    Code:
    >>> x = 1L<<40
    >>> x
    1099511627776L
    >>> `x`
    '1099511627776L'
    >>>
    Mark.
    programming language development: www.netytan.com Hula


IMN logo majestic logo threadwatch logo seochat tools logo