简体   繁体   English

为什么 Python 说我不能将字符串转换为整数,因为它有空字符串?

[英]Why does Python say that I can't convert a string into an integer because it has empty strings?

I'm making a procedure that takes in two coordinates as input, then calculating the midpoint.我正在制作一个将两个坐标作为输入的过程,然后计算中点。 However, when I try to change the input into an integer after just taking the part of the coordinate with the x and y values, it says ValueError: invalid literal for int() with base 10: '' <--That's an empty string by the way.但是,当我在仅使用 x 和 y 值的坐标部分后尝试将输入更改为整数时,它说 ValueError: invalid literal for int() with base 10: '' <--That's a empty string顺便一提。 Here's my code:这是我的代码:

def distance():
    p1=input('Input your first point:')
    p2=input('Input your second point:')
    split1=p1.find(',')
    x1=int(p1[2:split1-1])
    y1=p1[split1+1:-2]
    split2=p2.find(',')
    x2=p2[0:split2-1]
    y2=p2[split2+1:-1]
    x=x2-x1**2
    y=y2-y1**2
    d=(x+y)**.5
    print('This is the distance between those points',d)`

As others have said, int('') will yield this error because there is not a general consensus on what number '' should be converted to.正如其他人所说, int('')会产生这个错误,因为对于''应该转换成什么数字没有普遍的共识。

If you actually want a default value, consider using the following (where you want it to default to 0).如果您确实想要一个默认值,请考虑使用以下内容(您希望它默认为 0)。

value = ''
intvalue = int(value or '0')

# 0

value = '1'
intvalue = int(value or '0')

# 1

That being said, an easier way to accomplish splitting the coordinates like you want would be to use split()话虽如此,完成像您想要的那样分割坐标的更简单方法是使用split()

x,y = map(int, '1,2'.split(','))

If your input is actually of the form: (1, 2) , you will want to ignore the parentheses and only grab the numeric parts.如果您的输入实际上是以下形式: (1, 2) ,您将要忽略括号而只获取数字部分。

import re

val = '(1, 2)'
val = re.sub('\(|\)', '', val);
x,y = map(int, val.split(','))

Or more generically或者更一般地

val = '(-1, 2)' # or [-1, 2] or -1,2

val = re.search('\-?\d+\s*,\s*\-?\d+', val).group()
x,y = map(int, val.split(','))

For your specific example:对于您的具体示例:

def getxy(val):
    val = re.search('\-?\d+\s*,\s*\-?\d+', val)

    # Alert the user if invalid input was provided
    if val is None:
        raise Exception('Invalid input')

    # Convert all coordinates to integers
    return map(int, val.group().split(','))

x1, y1 = getxy(input('Input your first point:'))
x2, y2 = getxy(input('Input your second point:'))

I think you want to use something likesplit() instead of fancing indexing to parse your input:我认为您想使用split()类的东西而不是花式索引来解析您的输入:

def distance():
    p1=input('Input your first point:')
    p2=input('Input your second point:')
    x1, y1 = p1.split(',', 1)
    x1 = int(x1)
    y1 = int(y1)
    x2, y2 = p2.split(',', 1)
    x2 = int(x2)
    y2 = int(y2)
    x=x2-x1**2
    y=y2-y1**2
    d=(x+y)**.5
    print('This is the distance between those points',d)`

You are ignoring the first two characters of your point, so if the number has only two digits, you get an empty string.您忽略了点的前两个字符,因此如果该数字只有两位数字,则会得到一个空字符串。 Better split the string with split :split更好地拆分字符串:

p1 = '(1,4)'
x1, y1 = p1[1:-1].split(',')
x1 = int(x1)

I got it, I'm still not entirely sure what I did wrong, but I added a comma split clause.我明白了,我仍然不完全确定我做错了什么,但我添加了一个逗号分割子句。 In the beginning, I used replace like I did here, but it didn't work.一开始,我像这里一样使用了replace,但是没有用。 This time, it did!这一次,做到了! Thanks to everyone who tried to help.感谢所有试图提供帮助的人。 Here's my solution:这是我的解决方案:

def distance():
p1=input('Input your first point:')
p2=input('Input your second point:')
rp1=p1.replace('(','').replace(')','')
x1, y1 = rp1.split(',', 1)
x1 = int(x1)
y1 = int(y1)
rp2=p2.replace('(','').replace(')','')
x2, y2 = rp2.split(',', 1)
x2 = int(x2)
y2 = int(y2)
x=(x2-x1)**2
y=(y2-y1)**2
d=(x+y)**.5
print('This is the distance between those points',d)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我怎样才能在毫升中适应字符串? 因为它说我不能将字符串转换为浮点数? - how can i fit string in ml? because it say i cant convert string to float? 无法将字符串转换为整数-python - can't convert string to integer-python 无法在python中将字符串转换为整数 - Can´t convert string to integer in python 为什么我不能将 unicode 字符串转换为纯 python 字符串? - Why can't I convert unicode string to plain python string? 从 csv 读取 dataframe 时,为什么不能将 integer 转换为字符串? - Why can't I convert integer as string when reading in dataframe from csv? 如何在python中将通过UART发送的字符串转换为整数? - How can I convert a string sent over UART to integer in python? 我如何从 python 中的字符串数字转换为 integer 数字 - How can i convert to integer numbers from string numbers in python 如何在python中将字符串的索引转换为整数? - How can I convert the index of a string to an integer in python? 如何将字符串转换为 Python 列表中的 Integer 值? - How Can I Convert of String To Integer Value in a List in Python? 为什么 reverse(string[0:]) 在 python 中显示错误,为什么我不能用它代替 reverse(string[1:]) + string[0] - why does reverse(string[0:]) shows error in python , why can't i use this instead of reverse(string[1:]) + string[0]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM