开发者

python invalid literal error

开发者 https://www.devze.com 2023-02-17 06:21 出处:网络
so I ha开发者_JS百科ve this code data = input() m = data.split(\',\') for i in range(0, len(m)): print(int(m[i]) )

so I ha开发者_JS百科ve this code

data = input()
m = data.split(',')

for i in range(0, len(m)):

    print(int(m[i]) )

but then when i run it and type in "1,2,3", i get this error:

    print(int(m[i]))
ValueError: invalid literal for int() with base 10: '"1'

what did i do wrong?

using python 3


As you have your code, the input you type in should be numbers separated by commas. You do not have to include the quotes, just type 1,2,3 and nothing else. You only need the quotes only if you are writing actual code writing string literals. In this case, you are just taking input and it will already be strings.

The problem is that you are typing literally "1,2,3" and it tries to parse the first int the string, "1 which is invalid.


It seems you typed in literal quotation marks (") as part of your input; int() doesn't know how to parse those. You'll need to strip them out first:

data = input().strip('"')


Looks like there's an extra " character in your input. int() will only convert strings consisting solely of digits in the selected base (default base 10, so it accepts [0-9]). If any other characters appear in the string input, it raises this error.


Your input to input:

"1,2,3"

is appropriate for the Python 2 input. Python 3 input is like Python 2 raw_input and all its input is already considered a string.

0

精彩评论

暂无评论...
验证码 换一张
取 消