Re: "Invalid literal for int() with base 10": is it really a literal?
Chris Angelico wrote at 2023-5-26 18:29 +1000: > ... >However, if you want to change the wording, I'd be more inclined to >synchronize it with float(): > float("a") >Traceback (most recent call last): > File "", line 1, in >ValueError: could not convert string to float: 'a' +1 -- https://mail.python.org/mailman/listinfo/python-list
RE: "Invalid literal for int() with base 10": is it really a literal?
Roel, In order for the code to provide different error messages, it needs a way to differentiate between circumstances. As far as the int() function is concerned, it sees a string of characters and has no clue where they came from. In Python, int(input()) just runs input() first and creates a string and then passes it along to int(). You can of course argue there are ways to phrase an error message that may be less technicalese. -Original Message- From: Python-list On Behalf Of Roel Schroeven Sent: Friday, May 26, 2023 3:55 AM To: python-list@python.org Subject: "Invalid literal for int() with base 10": is it really a literal? Kevin M. Wilson's post "Invalid literal for int() with base 10?" got me thinking about the use of the word "literal" in that message. Is it correct to use "literal" in that context? It's correct in something like this: >>> int('invalid') Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'invalid' But something like this generates the same message: >>> int(input()) hello Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'hello' In cases like this there is no literal in sight. I'm thinking it would be more correct to use the term 'value' here: ValueError: invalid value for int() with base 10: 'hello' Does my reasoning make sense? -- "I love science, and it pains me to think that to so many are terrified of the subject or feel that choosing science means you cannot also choose compassion, or the arts, or be awed by nature. Science is not meant to cure us of mystery, but to reinvent and reinvigorate it." -- Robert Sapolsky -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: "Invalid literal for int() with base 10": is it really a literal?
On 2023-05-26 09:29, Chris Angelico wrote: On Fri, 26 May 2023 at 17:56, Roel Schroeven wrote: Kevin M. Wilson's post "Invalid literal for int() with base 10?" got me thinking about the use of the word "literal" in that message. Is it correct to use "literal" in that context? It's correct in something like this: >>> int('invalid') Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'invalid' But something like this generates the same message: >>> int(input()) hello Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'hello' In cases like this there is no literal in sight. I'm thinking it would be more correct to use the term 'value' here: ValueError: invalid value for int() with base 10: 'hello' Does my reasoning make sense? It's a ValueError, so the problem is with the value. I suppose "invalid notation" might work, but since the definition of what's acceptable to the int() constructor is the same as for a Python literal, it's not wrong to use that word. However, if you want to change the wording, I'd be more inclined to synchronize it with float(): float("a") Traceback (most recent call last): File "", line 1, in ValueError: could not convert string to float: 'a' You still need to mention the base because: >>> int('y', 36) 34 -- https://mail.python.org/mailman/listinfo/python-list
Re: Invalid literal for int() with base 10?
Keith Thompson writes: > "Kevin M. Wilson" writes: >> Ok, I'm not finding any info. on the int() for converting a str to an >> int (that specifies a base parameter)?! > > https://docs.python.org/3/library/functions.html#int [...] Or `print(int.__doc__)` at a Python ">>>" prompt, or `pydoc int` (or `pydoc3 int`) at a shell prompt. The latter may or may not be available. -- Keith Thompson (The_Other_Keith) keith.s.thompso...@gmail.com Will write code for food. void Void(void) { Void(); } /* The recursive call of the void */ -- https://mail.python.org/mailman/listinfo/python-list
Re: Invalid literal for int() with base 10?
On 2023-05-26, Grant Edwards wrote: > On 2023-05-25, Kevin M. Wilson via Python-list wrote: > >> Ok, I'm not finding any info. on the int() for converting a str to >> an int (that specifies a base parameter)?! > > Where are you looking? > > https://docs.python.org/3/library/functions.html#int And don't forget about the help() function: $ python Python 3.11.3 (main, May 8 2023, 09:00:58) [GCC 12.2.1 20230428] on linux Type "help", "copyright", "credits" or "license" for more information. >>> >>> help(int) Help on class int in module builtins: class int(object) | int([x]) -> integer | int(x, base=10) -> integer | | Convert a number or string to an integer, or return 0 if no arguments | are given. If x is a number, return x.__int__(). For floating point | numbers, this truncates towards zero. | | If x is not a number or if base is given, then x must be a string, | bytes, or bytearray instance representing an integer literal in the | given base. The literal can be preceded by '+' or '-' and be surrounded | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. | Base 0 means to interpret the base from the string as an integer literal. | >>> int('0b100', base=0) | 4 | | Built-in subclasses: | bool | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | [...] -- https://mail.python.org/mailman/listinfo/python-list
Re: "Invalid literal for int() with base 10": is it really a literal?
Op 26/05/2023 om 10:29 schreef Chris Angelico: However, if you want to change the wording, I'd be more inclined to synchronize it with float(): >>> float("a") Traceback (most recent call last): File "", line 1, in ValueError: could not convert string to float: 'a' I was looking for other ValueError-generating functions to find potentially better wording, and I somehow failed to think of float(), so thank you for mentioning it :) The ones I could think of were math functions like math.sqrt(); they give "ValueError: math domain error" which is rather less user friendly. -- "'How to Stop Worrying and Learn to Love the Internet': 1) everything that’s already in the world when you’re born is just normal; 2) anything that gets invented between then and before you turn thirty is incredibly exciting and creative and with any luck you can make a career out of it; 3) anything that gets invented after you’re thirty is against the natural order of things and the beginning of the end of civilisation as we know it until it’s been around for about ten years when it gradually turns out to be alright really. Apply this list to movies, rock music, word processors and mobile phones to work out how old you are." -- Douglas Adams -- https://mail.python.org/mailman/listinfo/python-list
Re: "Invalid literal for int() with base 10": is it really a literal?
On Fri, 26 May 2023 at 17:56, Roel Schroeven wrote: > > Kevin M. Wilson's post "Invalid literal for int() with base 10?" got me > thinking about the use of the word "literal" in that message. Is it > correct to use "literal" in that context? It's correct in something like > this: > > >>> int('invalid') > Traceback (most recent call last): >File "", line 1, in > ValueError: invalid literal for int() with base 10: 'invalid' > > But something like this generates the same message: > > >>> int(input()) > hello > Traceback (most recent call last): >File "", line 1, in > ValueError: invalid literal for int() with base 10: 'hello' > > In cases like this there is no literal in sight. > > I'm thinking it would be more correct to use the term 'value' here: > ValueError: invalid value for int() with base 10: 'hello' > Does my reasoning make sense? > It's a ValueError, so the problem is with the value. I suppose "invalid notation" might work, but since the definition of what's acceptable to the int() constructor is the same as for a Python literal, it's not wrong to use that word. However, if you want to change the wording, I'd be more inclined to synchronize it with float(): >>> float("a") Traceback (most recent call last): File "", line 1, in ValueError: could not convert string to float: 'a' ChrisA -- https://mail.python.org/mailman/listinfo/python-list
"Invalid literal for int() with base 10": is it really a literal?
Kevin M. Wilson's post "Invalid literal for int() with base 10?" got me thinking about the use of the word "literal" in that message. Is it correct to use "literal" in that context? It's correct in something like this: >>> int('invalid') Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'invalid' But something like this generates the same message: >>> int(input()) hello Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'hello' In cases like this there is no literal in sight. I'm thinking it would be more correct to use the term 'value' here: ValueError: invalid value for int() with base 10: 'hello' Does my reasoning make sense? -- "I love science, and it pains me to think that to so many are terrified of the subject or feel that choosing science means you cannot also choose compassion, or the arts, or be awed by nature. Science is not meant to cure us of mystery, but to reinvent and reinvigorate it." -- Robert Sapolsky -- https://mail.python.org/mailman/listinfo/python-list
Re: Invalid literal for int() with base 10?
Op 25/05/2023 om 23:30 schreef Kevin M. Wilson via Python-list: Ok, I'm not finding any info. on the int() for converting a str to an int (that specifies a base parameter)?! The picture is of the code I've written... And the base 10 paradigm involved?? years = int('y') # store for calculationValueError: invalid literal for int() with base 10: 'y'What is meant by "invalid literal"? I'm trying to convert srt to int, and I didn't know I needed to specify the base. Plus I haven't read anything that I need to specify the base for the int(). That error message might give the impression that you have to specify the base, but that's misleading. It's just trying to be helpful, showing what base was used because the allowed values depend on the base. For example, these will work: int('abcd', 16) # abcd is a valid hexadecimal number int('249', 10) int('249') # same as above, since base 10 is the default int('14', 8) These don't work: int('abcd', 10) # abcd is not a decimal number int('abcd') # same as above, since base 10 is the default int('249', 8) # 249 is not an octal number since 9 is not an octal digit An error message like "invalid literal for int(): '249'" would be very confusing because 249 seems to be a valid integer at first sight; ""invalid literal for int(): '249' with base 8" makes clear why it's not accepted. -- "I love science, and it pains me to think that to so many are terrified of the subject or feel that choosing science means you cannot also choose compassion, or the arts, or be awed by nature. Science is not meant to cure us of mystery, but to reinvent and reinvigorate it." -- Robert Sapolsky -- https://mail.python.org/mailman/listinfo/python-list
Re: Invalid literal for int() with base 10?
"Kevin M. Wilson" writes: > Ok, I'm not finding any info. on the int() for converting a str to an > int (that specifies a base parameter)?! https://docs.python.org/3/library/functions.html#int > The picture is of the code I've written... I don't see a picture. The mailing list probably does not accept attachments. (You don't need a picture anyway.) > And the base 10 paradigm involved?? The int() constructor takes a base parameter whose default value is 10. If you specify base=0, it will accept binary, octal, and hexadecimal numbers in addition to decimal. All this is explained in the link I gave you. > years = int('y') # store for calculationValueError: invalid > literal for int() with base 10: 'y'What is meant by "invalid literal"? '42' is a valid literal for int(). 'y' is not. What value did you expect int('y') to give you? Perhaps you have a variable named 'y' containing a string? If so, you might want something like int(y) or int(f{'y'}), but int('y') passes the literal string 'y', which has nothing to do with a variable of that name. > I'm trying to convert srt to int, Do you mean "str to int"? > and I didn't know I needed to specify the base. You don't. If you don't specify the base, it defaults to 10. > Plus I haven't read anything that I need to specify > the base for the int(). Attached is the code, showing the code and > the execution of said code. Any attachment was removed. > "When you pass through the waters, I will > be with you: and when you pass through the rivers, they will not sweep > over you. When you walk through the fire, you will not be burned: the > flames will not set you ablaze." Isaiah 43:2 You can add a signature to all your messages if you like, but it will be very helpful if you introduce it with a line consisting of "-- ", as I've done here. It would also be very helpful if you introduce line breaks into your message, particularly before and after any included code. The formatting made your message difficult to read. -- Keith Thompson (The_Other_Keith) keith.s.thompso...@gmail.com Will write code for food. void Void(void) { Void(); } /* The recursive call of the void */ -- https://mail.python.org/mailman/listinfo/python-list
Re: Invalid literal for int() with base 10?
On 2023-05-25, Kevin M. Wilson via Python-list wrote: > Ok, I'm not finding any info. on the int() for converting a str to > an int (that specifies a base parameter)?! Where are you looking? https://docs.python.org/3/library/functions.html#int > The picture is of the code I've written... And the base 10 paradigm > involved?? I've no clue what that sentence means. > years = int('y') # store for calculationValueError: > invalid literal for int() with base 10: 'y'What is meant by "invalid > literal"? It means that the string 'y' isn't an integer literal. The strings '123' and '-4' are integer literals. https://docs.python.org/3/reference/expressions.html?highlight=integer%20literal#literals > I'm trying to convert srt to int, and I didn't know I needed to > specify the base. You don't need to unless you want a base other than 10. > Plus I haven't read anything that I need to specify the base for the int(). Don't know what you mean there. > Attached is the code, showing the code and the execution of said > code. Sorry, I don't see attachments. Include code in posts. > "When you pass through the waters, I will be with you: and > when you pass through the rivers, they will not sweep > over you. When you walk through the fire, you will not be burned: > the flames will not set you ablaze." Isaiah 43:2 Huh? -- https://mail.python.org/mailman/listinfo/python-list
Re: Invalid literal for int() with base 10?
On 2023-05-25 22:30, Kevin M. Wilson via Python-list wrote: Ok, I'm not finding any info. on the int() for converting a str to an int (that specifies a base parameter)?! The picture is of the code I've written... And the base 10 paradigm involved?? years = int('y') # store for calculationValueError: invalid literal for int() with base 10: 'y'What is meant by "invalid literal"? I'm trying to convert srt to int, and I didn't know I needed to specify the base. Plus I haven't read anything that I need to specify the base for the int(). '12' is a string that contains 2 digits, which together represent the number 12. 'y' is a string that contains a letter, which doesn't represent a number. Perhaps what you meant is that y is a variable that contains a string, in which case what you want is int(y). Attached is the code, showing the code and the execution of said code. There's no code attached; this list automatically strips attachmentments. -- https://mail.python.org/mailman/listinfo/python-list
Re: Invalid literal for int() with base 10?
On Fri, 26 May 2023 at 10:26, Kevin M. Wilson via Python-list wrote: > > Ok, I'm not finding any info. on the int() for converting a str to an int > (that specifies a base parameter)?! The picture is of the code I've > written... And the base 10 paradigm involved?? years = int('y') # store for > calculation ValueError: invalid literal for int() with base 10: 'y' > Imagine giving this to a human. "How many years did you say?" "Oh, y years." Is that a reasonable way to say a number of years? No. It's an invalid way of specifying a number of years. Python is a little more technical in the way it describes it, but the fact is unchanged. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Invalid literal for int() with base 10?
Ok, I'm not finding any info. on the int() for converting a str to an int (that specifies a base parameter)?! The picture is of the code I've written... And the base 10 paradigm involved?? years = int('y') # store for calculation ValueError: invalid literal for int() with base 10: 'y' What is meant by "invalid literal"? I'm trying to convert str to int, and I didn't know I needed to specify the base. Plus I haven't read anything that I need to specify the base for the int(). Attached is the code, showing the code and the execution of said code. Sorry, got pissed and didn't check all the content I sent! "When you pass through the waters, I will be with you: and when you pass through the rivers, they will not sweep over you. When you walk through the fire, you will not be burned: the flames will not set you ablaze." Isaiah 43:2 On Thursday, May 25, 2023 at 05:55:06 PM MDT, Kevin M. Wilson via Python-list wrote: Ok, I'm not finding any info. on the int() for converting a str to an int (that specifies a base parameter)?! The picture is of the code I've written... And the base 10 paradigm involved?? years = int('y') # store for calculationValueError: invalid literal for int() with base 10: 'y'What is meant by "invalid literal"? I'm trying to convert srt to int, and I didn't know I needed to specify the base. Plus I haven't read anything that I need to specify the base for the int(). Attached is the code, showing the code and the execution of said code. "When you pass through the waters, I will be with you: and when you pass through the rivers, they will not sweep over you. When you walk through the fire, you will not be burned: the flames will not set you ablaze." Isaiah 43:2 -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Invalid literal for int() with base 10?
Ok, I'm not finding any info. on the int() for converting a str to an int (that specifies a base parameter)?! The picture is of the code I've written... And the base 10 paradigm involved?? years = int('y') # store for calculationValueError: invalid literal for int() with base 10: 'y'What is meant by "invalid literal"? I'm trying to convert srt to int, and I didn't know I needed to specify the base. Plus I haven't read anything that I need to specify the base for the int(). Attached is the code, showing the code and the execution of said code. "When you pass through the waters, I will be with you: and when you pass through the rivers, they will not sweep over you. When you walk through the fire, you will not be burned: the flames will not set you ablaze." Isaiah 43:2 -- https://mail.python.org/mailman/listinfo/python-list
Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'
Matthias Bläsing wrote: Am Wed, 28 May 2008 10:41:51 -0700 schrieb davidj411: I like the str2num function approach, but then i get left with a float that has more than 2 decimal spaces , i.e. 11.50 becomes 11.449 and round will not fix that. Welcome to the wonderful world of floating point numbers. For your usage you want 10-based numbers. Have a look at the decimal module: from decimal import Decimal a = Decimal("11.45") a Decimal("11.45") str(a) '11.45' a + 1 Decimal("12.45") a + Decimal("1.55") Decimal("13.00") HTH Matthias -- http://mail.python.org/mailman/listinfo/python-list Thanks for the tip, Matthias. I knew that there had to be a way to handle arbitrary precision numbers. -- Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman -- http://mail.python.org/mailman/listinfo/python-list
Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'
Am Wed, 28 May 2008 10:41:51 -0700 schrieb davidj411: > I like the str2num function approach, but then i get left with a float > that has more than 2 decimal spaces , i.e. 11.50 becomes > 11.449 and round will not fix that. Welcome to the wonderful world of floating point numbers. For your usage you want 10-based numbers. Have a look at the decimal module: >>> from decimal import Decimal >>> a = Decimal("11.45") >>> a Decimal("11.45") >>> str(a) '11.45' >>> a + 1 Decimal("12.45") >>> a + Decimal("1.55") Decimal("13.00") HTH Matthias -- http://mail.python.org/mailman/listinfo/python-list
Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'
On May 28, 2:22 am, Kam-Hung Soh <[EMAIL PROTECTED]> wrote: > David Jackson wrote: > > i used the csv module and saved its contents to a list. > > > ['Date', 'No.', 'Description', 'Debit', 'Credit'] > > ['3/17/2006', '5678', 'ELECTRONIC PAYMENT', '', '11.45'] > > ['3/04/2007', '5678', 'THE HOME DEPOT 263 SomeCity FL', '', '25.40'] > > > the credit/debit fields are strings. > > what should i have done within the CSV module to make numbers appear as > > numbers? > > how can i remove the quotes to make them numbers? i realize i posted a > > solution to this once before (same posting thread) but i am thinking > > there is a better method. > > There doesn't seem to be a way to describe how specific columns should > be processed in the csv module. You could define a conversion function > that "guesses" the best conversion, for example: > > def str2num(datum): > try: > return int(datum) > except: > try: > return float(datum) > except: > return datum > > for row in csv.reader(file(r'Transaction.csv')): > [str2num(cell) for cell in row] > > ['Date', 'No.', 'Description', 'Debit', 'Credit'] > ['3/17/2006', 5678, 'ELECTRONIC PAYMENT', '', 11.449] > ['3/04/2007', 5678, 'THE HOME DEPOT 263 SomeCity FL', '', > 25.399] > > -- > Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman I like the str2num function approach, but then i get left with a float that has more than 2 decimal spaces , i.e. 11.50 becomes 11.449 and round will not fix that. -- http://mail.python.org/mailman/listinfo/python-list
Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'
David Jackson wrote: i used the csv module and saved its contents to a list. ['Date', 'No.', 'Description', 'Debit', 'Credit'] ['3/17/2006', '5678', 'ELECTRONIC PAYMENT', '', '11.45'] ['3/04/2007', '5678', 'THE HOME DEPOT 263 SomeCity FL', '', '25.40'] the credit/debit fields are strings. what should i have done within the CSV module to make numbers appear as numbers? how can i remove the quotes to make them numbers? i realize i posted a solution to this once before (same posting thread) but i am thinking there is a better method. There doesn't seem to be a way to describe how specific columns should be processed in the csv module. You could define a conversion function that "guesses" the best conversion, for example: def str2num(datum): try: return int(datum) except: try: return float(datum) except: return datum for row in csv.reader(file(r'Transaction.csv')): [str2num(cell) for cell in row] ['Date', 'No.', 'Description', 'Debit', 'Credit'] ['3/17/2006', 5678, 'ELECTRONIC PAYMENT', '', 11.449] ['3/04/2007', 5678, 'THE HOME DEPOT 263 SomeCity FL', '', 25.399] -- Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman -- http://mail.python.org/mailman/listinfo/python-list
Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'
En Tue, 27 May 2008 13:00:05 -0300, David Jackson <[EMAIL PROTECTED]> escribió: i used the csv module and saved its contents to a list. ['Date', 'No.', 'Description', 'Debit', 'Credit'] ['3/17/2006', '5678', 'ELECTRONIC PAYMENT', '', '11.45'] ['3/04/2007', '5678', 'THE HOME DEPOT 263 SomeCity FL', '', '25.40'] the credit/debit fields are strings. what should i have done within the CSV module to make numbers appear as numbers? how can i remove the quotes to make them numbers? i realize i posted a solution to this once before (same posting thread) but i am thinking there is a better method. What do you want to do with those empty strings? Convert them to zeros? Suppose your list is named `rows`: for i,row in enumerate(rows): if not i: continue # skip titles row[3] = float(row[3] or 0) row[4] = float(row[4] or 0) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'
On Feb 28, 5:56 pm, davidj411 <[EMAIL PROTECTED]> wrote: > i am parsing a cell phone bill to get a list of all numbers and the > total talktime spend on each number. > > (snipped) > > I actually found a good solution. > (snipped) If you post 1-2 samples of the cell phone bill input, I am sure you'll get much better solutions in terms of clarity, simplicity and elegance, commonly known as "pythonicity" :) George -- http://mail.python.org/mailman/listinfo/python-list
Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'
On Fri, 29 Feb 2008 13:32:15 -0800 (PST) "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > > > You have to get rid of the double quotes first. > > you mean replace them with nothing? > > li[4].replace('"','') Sure, that will do. However, look at the csv module for another way of handling this. > once i do that, i should be able to use them as numbers. You still need to apply int() or float() to the result. -- D'Arcy J.M. Cain <[EMAIL PROTECTED]> | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'
"davidj411" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] |i am parsing a cell phone bill to get a list of all numbers and the | total talktime spend on each number. | | i already have a unique list of the phone numbers. | now i must go through the list of numbers and add up the totals for | each number. | here is the function i wrote to get one number at a time's total | talktime. | | def getsinglenumbertalktime(number,talktime): | for line in file[0:-2]: ... | | talktime = talktime + li[5] | return talktime It would appear that you are calling this function and rescanning scanning file for each number. It would be more efficient to scan the file once, for each line parsing out the number and minutes and incrementing the minutes for that number. Also, if you had printed repr(li[5]) and len(li[5]) instead of or in addition to just li[5] (which prints str(li[5]), >>> a='"2"' >>> print a, repr(a), len(a) "2" '"2"' 3 you might have seen for yourself the problem that the string contains quote marks and not just digits. Repr and len are useful debugging aids. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'
> You have to get rid of the double quotes first. you mean replace them with nothing? li[4].replace('"','') once i do that, i should be able to use them as numbers. -- http://mail.python.org/mailman/listinfo/python-list
Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'
davidj411 wrote: > i am parsing a cell phone bill to get a list of all numbers and the > total talktime spend on each number. > > i already have a unique list of the phone numbers. > now i must go through the list of numbers and add up the totals for > each number. > on the bill, each line has a few fields,one field containing the phone > number, another field containing the number of minutes on that call. > the bill is comma delimited. > > here is the function i wrote to get one number at a time's total > talktime. > > def getsinglenumbertalktime(number,talktime): > for line in file[0:-2]: >if number in line: > li=line.split(',') > if len(li)==6 and li[5]!="Minutes" : > print "talktime type: " + str(type (talktime)) > #li[5]=fpformat.fix(li[5],0) > > print li[5] + "li[5] type: " + str(type(li[5])) > newvar = int(li[5]) > print (type(newvar)) > print li[5] > talktime = talktime + li[5] > return talktime > > here is the output with error that i get back. > > talktime type: > "2"li[5] type: > Traceback (most recent call last): > File "", line 1, in > File "c:\path\inprog\all_t_mob_nums.py", line 74, in > getsinglenumbertalktime('"800-218-2644"',talktime) > File "c:\path\inprog\all_t_mob_nums.py", line 66, in > getsinglenumbertalktime > newvar = int(li[5]) > ValueError: invalid literal for int() with base 10: '"2"' > > > here is the question: > > How can i convert a string number like "2" to a true number that can > be added. > I have tried using pfformat, float(), and int() - all with no good > results. > this seems like is should be simple, but it just plain isn't. > > > I actually found a good solution. > basically, take each entry and add it to a list. > then iterate through the list , converting each item to int(). > then add them to sum them all up. > > FINAL SOLUTION: > def getsinglenumbertalktime(number,talktime): > num_of_calls=0 > num_mins=[] > for line in file[0:-2]: > #print "LINE: " + line > #print number in line > if number in line: > num_of_calls += 1 > #print number,num_of_calls > li=line.strip("\n") > #print "stripped:" + line > li=li.split(',') > #print "split: " + str(li) > #print "len of li: " + str(len(li)) + str(num_of_calls) > if len(li)==7 and li[5]!="Minutes" : > #print "talktime type: " + str(type (talktime)) > #print li[4] + "li[4] type: " + str(type(li[5])) > #newvar = fpformat.fix(li[4],0) > #print (type(newvar)) > #print "len 7: " + str(type(li[6])) > num_mins.append(li[6]) > #talktime = talktime + int(a) > > if len(li)==6 and li[5]!="Minutes" : > #print "talktime type: " + str(type (talktime)) > #print li[5] + "li[5] type: " + str(type(li[5])) > #newvar = fpformat.fix(li[4],0) > #print (type(newvar)) > #print "len 6: " + str(type(li[5])) > num_mins.append(li[5]) > #talktime = talktime + int(a) > #return talktime , num_of_calls > x=0 > #print "this" + str(number) + str(num_mins) > for a in num_mins: > b=int(a) > x=x+b > print str(number), str(x), str(type(x)) > > output should look like this (parts of script are not included) > 555-555- replaced the innocent :P): > 555-555- 19 > 555-555- 6 > 555-555- 3 > 555-555- 3 > 555-555- 2 > 555-555- 52 If the file is quote and comma delimited, you should be using the csv module to do your reading and stripping of the quotes. Should make things MUCH easier. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'
On Thu, 28 Feb 2008 14:56:10 -0800 (PST) davidj411 <[EMAIL PROTECTED]> wrote: > ValueError: invalid literal for int() with base 10: '"2"' > > > here is the question: > > How can i convert a string number like "2" to a true number that can > be added. You have to get rid of the double quotes first. -- D'Arcy J.M. Cain <[EMAIL PROTECTED]> | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'
i am parsing a cell phone bill to get a list of all numbers and the total talktime spend on each number. i already have a unique list of the phone numbers. now i must go through the list of numbers and add up the totals for each number. on the bill, each line has a few fields,one field containing the phone number, another field containing the number of minutes on that call. the bill is comma delimited. here is the function i wrote to get one number at a time's total talktime. def getsinglenumbertalktime(number,talktime): for line in file[0:-2]: if number in line: li=line.split(',') if len(li)==6 and li[5]!="Minutes" : print "talktime type: " + str(type (talktime)) #li[5]=fpformat.fix(li[5],0) print li[5] + "li[5] type: " + str(type(li[5])) newvar = int(li[5]) print (type(newvar)) print li[5] talktime = talktime + li[5] return talktime here is the output with error that i get back. talktime type: "2"li[5] type: Traceback (most recent call last): File "", line 1, in File "c:\path\inprog\all_t_mob_nums.py", line 74, in getsinglenumbertalktime('"800-218-2644"',talktime) File "c:\path\inprog\all_t_mob_nums.py", line 66, in getsinglenumbertalktime newvar = int(li[5]) ValueError: invalid literal for int() with base 10: '"2"' here is the question: How can i convert a string number like "2" to a true number that can be added. I have tried using pfformat, float(), and int() - all with no good results. this seems like is should be simple, but it just plain isn't. I actually found a good solution. basically, take each entry and add it to a list. then iterate through the list , converting each item to int(). then add them to sum them all up. FINAL SOLUTION: def getsinglenumbertalktime(number,talktime): num_of_calls=0 num_mins=[] for line in file[0:-2]: #print "LINE: " + line #print number in line if number in line: num_of_calls += 1 #print number,num_of_calls li=line.strip("\n") #print "stripped:" + line li=li.split(',') #print "split: " + str(li) #print "len of li: " + str(len(li)) + str(num_of_calls) if len(li)==7 and li[5]!="Minutes" : #print "talktime type: " + str(type (talktime)) #print li[4] + "li[4] type: " + str(type(li[5])) #newvar = fpformat.fix(li[4],0) #print (type(newvar)) #print "len 7: " + str(type(li[6])) num_mins.append(li[6]) #talktime = talktime + int(a) if len(li)==6 and li[5]!="Minutes" : #print "talktime type: " + str(type (talktime)) #print li[5] + "li[5] type: " + str(type(li[5])) #newvar = fpformat.fix(li[4],0) #print (type(newvar)) #print "len 6: " + str(type(li[5])) num_mins.append(li[5]) #talktime = talktime + int(a) #return talktime , num_of_calls x=0 #print "this" + str(number) + str(num_mins) for a in num_mins: b=int(a) x=x+b print str(number), str(x), str(type(x)) output should look like this (parts of script are not included) 555-555- replaced the innocent :P): 555-555- 19 555-555- 6 555-555- 3 555-555- 3 555-555- 2 555-555- 52 -- http://mail.python.org/mailman/listinfo/python-list