我对Python语法有疑问。
解析字符串并将其转换为浮点数时,我遇到了一个问题。
我有代码
print "Please enter in x1 and y1 separated by a comma"
in1 = input()
sp1 = str(in1).split(',')
x1 = sp1[0]
如果我进入
5.4,3.2
并打印出x1,我得
(5.4
这个额外的括号使我很难转换成浮点进行进一步计算。 但是,如果我基于小数分割,例如
print "Please enter in x1 and y1 separated by a comma"
in1 = input()
sp1 = str(in1).split('.')
我可以将x1打印为
5
我没有得到好的括号,但我也没有得到正确的数字。
非常感谢任何帮助,谢谢
答案 0 :(得分:2)
问题似乎是input()
评估表达式并返回得到评估的内容。 5.4,3.2
似乎被评估为元组。
解决方案是使用raw_input()
代替,它只会将输入的文本作为字符串返回。或者如果可能的话,使用Python 3,它将input()
改为raw_input()
为Python 2做的事情。
答案 1 :(得分:1)
看起来当用逗号提交输入值时,你会得到一个元组。而不是将其转换为字符串&拆分它直接使用索引访问元素。
<强>实施例强>
print "Please enter in x1 and y1 separated by a comma"
sp1 = input()
print sp1, type(sp1)
x1 = sp1[0]
print x1
<强>输出:强>
(5.4, 3.2) <type 'tuple'>
5.4
答案 2 :(得分:0)
以下是如何执行此操作的方法:
print ("Please enter in x1 and y1 separated by a comma : ")
in1 = input()
sp1 =" ".join(str(in1).split(','))
print(sp1)
输入
1.1,1.2
输出
1.1 1.2