1

I have a question regarding Python syntax.

When parsing a string and casting it to a float, I am running in to an issue.

I have the code

print "Please enter in x1 and y1 separated by a comma"
in1 = input()
sp1 = str(in1).split(',')

x1 = sp1[0]

If I enter in

5.4,3.2

and print out x1, I get

(5.4

This extra parenthesis makes it hard for me to convert into a floating point for further calculation. However, if I split based on a a decimal, such as

print "Please enter in x1 and y1 separated by a comma"
    in1 = input()
    sp1 = str(in1).split('.')

I am able to print x1 as

5

I do not get the parenthesis which is good, however I am not getting the correct number either.

Any help would be greatly appreciated, thank you

Ububtunoob
  • 103
  • 8
  • I followed your steps and cannot reproduce the issue. When entering `5.4,3.2`, splitting the string at `,` and assigning the first part to x1, x1 is `5.4` for me (Python 3.6) – Felk Apr 03 '18 at 09:36
  • 2
    As mentioned here `input()` evaluates what you enter as Python code and then thinks it's a tuple because of the comma. Use `raw_input()`. https://stackoverflow.com/a/4960216/102315 – Alper Apr 03 '18 at 09:38
  • Any reason you want to convert to `str` first and then extract the number? Python has done it for you already, so you can just do `x1, y1 = in1` – Paul Panzer Apr 03 '18 at 09:54

3 Answers3

2

The problem seems to be that input() evaluates the expression and returns whatever got evaluated. 5.4,3.2 seems to be evaluated to a tuple.

The solution is to use raw_input() instead, which will just return the inputted text as a string. Or use Python 3, if possible, which changed input() to do what raw_input() does for Python 2.

Felk
  • 7,720
  • 2
  • 35
  • 65
1

Looks like when submitting a value in input with a comma you get a tuple. Instead of converting it to a string & splitting it access the element directly using index.

Ex:

print "Please enter in x1 and y1 separated by a comma"
sp1 = input()
print sp1, type(sp1)
x1 = sp1[0]
print x1

Output:

(5.4, 3.2) <type 'tuple'>
5.4
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

Here is how you can do this :

print ("Please enter in x1 and y1 separated by a comma : ")
in1 = input()
sp1 =" ".join(str(in1).split(','))
print(sp1)

intput

1.1,1.2

output

1.1 1.2
toheedNiaz
  • 1,435
  • 1
  • 10
  • 14