Converting strings to floats in Python without relying on specific locales

When trying to convert a string to a float, I encounter various input formats like '1234,5', '1234.5', '1 234,5', or '1,234.5'. The challenge is that I can't adjust the locale decimal pointer or thousands separator in advance because the data I receive may differ.

Is there a method, library, or workaround available for parsing and converting these locale-specific values to floats regardless of the locale used?

P.S. Are there any solutions for handling a similar issue with dates?

TIA.

Answer №1

If you're trying to figure out which character in a string is the thousands separator and which is the decimal point, there are some guidelines you can follow. However, there are certain cases where it's not so easy:

  • First, check for the last occurrence of either . or ,. If one of these characters appears more than once, then the number does not have a decimal point, and that particular character serves as the thousands separator.
  • If there is exactly one instance of each character in the string, then the last one is typically the decimal point.
  • In situations where there is only one point/comma present, such as in 123.456 or 123,456, determining whether it represents 123456 or 123.456 can be challenging. However, if the number, like 123.45, has a non-multiple of three digits after the potential thousands separator, it is likely a decimal point.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Python Json.decoder.JSONDecodeError: Anticipating a ',' delimiter:

When attempting to load a dictionary into json, I encountered an error. strsdc = ''' {"ext":{"amznregion":["useast"],"someURL":"https://som_url.com/x/px/Iyntynt/{"c":"client&qu ...

Error encountered in macOS python 2.7: IndexError occurs due to list index exceeding range

#!/usr/bin/env python import scapy.all as scapy import time import sys import argparse def get_arguments(): parser = argparse.ArgumentParser() parser.add_argument('-t', '--target', dest='target_ip', help='[+] I ...

Half of the image obscured by elif conditions

I need help creating an image with quadrants that have different color variations. I've managed to complete half of the image, but the other half seems to blur without any error messages. Any suggestions on what might be causing this issue? My goal is ...

Warning: The use of executable_path is no longer recommended. Please instantiate a Service object instead. How can I proceed?

from bs4 import BeautifulSoup import requests from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from selenium.webdriver.common.desired_capabilities import DesiredCapabilities import time from selenium.webdri ...

I'm struggling with a dataclass error and can't seem to find a solution

Hi everyone, I encountered an issue with dataclass. As a beginner in coding, it's possible that I am facing a problem with inheritance. My main goal is to hide init. However, after importing dataclass, I received the following error in VSCode: "Fields ...

Is there a way to nudge a turtle into motion from the finishing line of another?

One example is creating a hexagon and a pentagon using turtle graphics, where the pentagon starts from a different endpoint than the beginning of the hexagon. hexTurtle = turtle.Turtle() def drawHexagon(hexTurtle, size): hexTurtle.pendown() hexT ...

Finding the minimum value of an average within a Pandas GroupBy operation

My dataset, "Star Wars People df," contains the following columns: columns = [name, height, mass, birth_year, gender, homeworld] Name acts as the index I am looking to calculate the planet with the lowest average mass index of its inhabitants and determi ...

Python 3 identify the true condition in an "or" operation

Currently, I have a working piece of code that fulfills my requirements, but I am unsure if there is a more efficient way to achieve the desired outcome. Here is the code snippet: def eitherOne(image1, image2): curIm1 = pyautogui.locateOnScreen(image1 ...

In the Python version 2.7.1, there seems to be a syntax error when using conditional assignments, but interestingly, this issue does not occur in 2

Code works in Python 2.7.3 but not in 2.7.1. Do I need to rewrite it using a traditional if-else format for compatibility with 2.7.1? Or is there something else causing the syntax error? Error in Python 2.7.1 (works in 2.7.3): stub=(sys.argv[ix].lowe ...

Transmit image data as a string and decrypt

I have a client running Python 2.7 and the application does not have the capability to send files to the server, so I am sending pictures as strings. with open(path, "rb") as imageFile: str = b64encode(imageFile.read()) When attempting to decode ...

Determine the highest product possible by multiplying two columns following the groupby operation

I currently have a dataframe structured as shown below: item width length 0 X 4 1 1 F 15 4 2 R 6 3 3 X 3 10 4 F 10 19 My goal is to display the width and length of the l ...

What is the process for performing a task prior to an HTTP POST request in node.js?

I'm just starting out with nodejs and my goal is to upload an image along with some data to a nodejs API. However, before saving the data to Mongo DB, I need to process the uploaded image using a Python class and then save the results to the database. ...

Utilizing Python for extracting syntactic features with CoreNLP: A step-by-step guide

I am looking to retrieve syntactic information from a sentence. Here is what I have attempted so far: corenlp_dir = "/home/corenlp-python/stanford-corenlp-full-2013-11-12/" parser = corenlp.StanfordCoreNLP(corenlp_path=corenlp_dir) result_json = json.loa ...

Reading lines from a serial connection in Python using the ord() function

Currently, I am facing an issue with my Raspberry Pi code. I am trying to read the serial port data and convert the result value to hexadecimal format, but the code is failing due to an ord() error. The same code used to work perfectly in the past, but aft ...

Tips for utilizing the functionalities of the superclass

When the SMS_Store inherits the Message, I encounter an error every time I call the parent method: NoneType object does not have attribute 'read_message'. Additionally, the object stored in the list returns a None value. Strange, right? class ...

When executing a migration, tables are identified, but unfortunately they are not being generated in the database

After running a migration to create the SQLite tables for a cookiecutter Flask app, I encountered an issue. Even though the database file is present and accessible, the tables do not seem to exist. When attempting to create a user, an error stating "no s ...

Tips for carrying on with graphing in python within the current window

Help needed: I'm struggling to keep all my plots in the same window without having to close it each time a new plot is generated. Is there a way to navigate through the different plots using arrows at the bottom of the plot window? Here's the cod ...

Behaviors following inputting arguments into a function in Python

I have a question about the following code snippet: def add_minor(person): person.append('math') def switch_majors(person): person=['physics'] person.append('economics') John=['computer_science'] Tim=John ...

Can you please share a way to extract a specific number from a span class using Python with Selenium?

How can I extract a specific number from a span class in Python using Selenium? <button class="sqdOP yWX7d _8A5w5 " type="button">외 <span>59</span>명</button> I need to retrieve the value "59" <button class="sqdOP yW ...

Error encountered in PyDev regarding an attribute

Just recently, I installed PyDev for Eclipse Oxygen 3 on my Windows 10 system. As a beginner programmer, I am currently working on writing basic programs while following a "learn to code" book. The example I am currently focusing on involves using a module ...