1

I am trying to convert decimal geographic coordinates as strings to a float. The coordinates are in a csv like this '51213512'. With my Python script I am just reading the coordinates and add the '.'. If I am not adding the comma the rest of my script isn't working.

I already tried a few things but nothing worked for me. This is what I got so far.

latitude=float(long('51.213512'))

The Result is a ValueError:

ValueError: invalid literal for long() with base 10: 'Long'
3
  • You mention a comma. Are you adding a comma or a decimal point (full stop, dot, etc.)? That should make a big difference. Commented Feb 8, 2019 at 20:36
  • I suspect that you're trying to convert a header line (possibly with header values "Lat" and "Long") in your input file to float. You need to find a way to skip that header line and just convert the values. Commented Feb 9, 2019 at 9:08
  • @MarkDickinson Yes this was the problem. There were invisible characters Commented Feb 9, 2019 at 12:04

2 Answers 2

1

not too sure why you are using long in this examply if you want to convert this variable to a float just use the float function on its own, you seem to be confusing the long and float functions. dont use both you will be confusing python (basically dosent know what to do because your giving it 2 arguments at once)

I recommend just using the float function on its own. This will avoid confusion

latitude = float('51.2135512')
Sign up to request clarification or add additional context in comments.

2 Comments

I am confused because of the traceback. If I am using your code it says: 'ValueError: could not convert string to float: Long'
@Lukas: Works for me, in Python 2.7.15. Is this part of a larger piece of code? If so, please post the entire function. Just edit your question and add the code.
1

Get rid of the 'long' and it should work

latitude = float('51.213512')

Edit: Okay, since you're getting the coordinates and manually converting to decimal strings, all you need to do is use the code I said originally. The long function converts integers or strings of integers to long types, not float types.

>>> long(5)
5L
>>> long('5')
5L
>>> long(5.5)
5L
>>> long('5.5')
ValueError: invalid literal for long() with base 10: '5.5'

3 Comments

I already tried. But this is the output ValueError: could not convert string to float: Long
@Lukas would you post how you're generating the geographic coordinates?
@Lukas: start Python. At the prompt, enter float('5.125') and press return. What is the output you get? If it is anything else but 5.125 something is very wrong with your Python installation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.