How to use Python comma instead of a dot

Asked

Viewed 12,076 times

1

The Brazilian system, unlike the American system, uses the comma to separate decimals, but like Python was made in a country that uses the point to separate decimals, the programs, when we use the function print, uses dots. How do I use comma instead?

As an example: I ask the user to enter with his salary, if he does not take knowledge of the use of the point, the program will give error and the user will find as BUG, then how do I change it?

2 answers

6

Quick, dirty approach - "str.replace":

Python’s string handling facilities allow you to turn the number into a string, and replace the "." character with the ",". Just do something like: print(str(1234.56).replace(".", ","))

Correct approach: "locale"

Although this technique is simple and works well from the end user’s point of view, it is not considered a good practice - because semantically you no longer have a number - you are exchanging characters in a string. The biggest problem however is that tie your code in a specific format. It is one thing to be making a small program of about 300 lines for personal use. Another is to be programming a complex system, which will have to serve users in several different languages and countries, always "doing the right thing". And this is the reality of both who codes Open Source projects, and who is in any company that aims to grow a little bit.

Well, of course, in so many decades of computing there are standardized and correct ways to write generic code that can format numbers (and write things like month and day names of the week, accent word ordering, etc...) that work for several different countries and languages, just changing the configuration. These forms meet the name "locale" - and in Python are usable through the package of the same name as the standard library: locale.

To format numbers as we used in Brazil you need the following steps:

  • import the locale package
  • change the "locale" setting for numbers to use Brazilian Portuguese with a call to locale.setlocale
  • convert your number to string using the function locale.format

So, in fact, if the program will be fixed in Brazilian Portuguese, it is very simple. Ah, to read back a number typed by the user can use the function locale.atof to convert the number correctly, according to the country of the program.

Below is a small program that runs a print and input using the Brazilian locale (pt_BR) and the American (en_US) in sequence:

import locale


def body():
    suggestion = 3500
    str_value = input(
        "Digite a pretenção salarial (exemplo: R${}): ".format(
            locale.format("%.2f", suggestion)
        )
    )
    value = locale.atof(str_value)
    print(
        "Valor numérico interno: {}. Valor formatado: {}".format(
            value,
            locale.format("%.2f", value, grouping=True, monetary=True)
        )
    )


def main():
    for locale_name in ("pt_BR", "en_US"):
        locale.setlocale(locale.LC_ALL, (locale_name, ""))
        print("\n\nExemplo usando o locale {}: \n".format(locale_name))
        body()


if __name__ == "__main__":
    main()

Some details: the functions locale.format and locale.format_string use Python’s "old" numeric formatting syntax - the one using the operator % to format strings - inherited from printf of the language C. You can refer to the details of this formatting in the documentation, but the important thing is to know that you must provide a formatting string starting with the character "%", of the desired total number size, followed by a "." followed by the number of houses after the desired comma and finally the character "f" - that is, our "%. 02f" indicates that we will format a decimal number of a size that does not matter, but always with two boxes after the comma.

Another detail is that in this example I used the "format" method that was recommended to format strings in recent years in Python - before leaving Python 3.6 - with Python 3.6 you can use the "fstrings" - strings in which the quotes are prefixed with the letter "f" instead of calling the method "format" - and insert Python expressions directly between keys ({ }) within the string itself. The final print line in Python 3.6 would be: print(f"Valor numérico interno: {value}. Valor formatado: {locale.format("%.2f", value, grouping=True, monetary=True)}")

Note that the program follows more or less the good practice of "being tolerant to the entries it receives and being strict with what it prints back" - it does not matter if the user enters the separator of the thousands (the "." in the case of the numbers as we use in Brazil) - it formats back with this tab, using the optional "grouping" parameter of the function locale.format.

See full documentation of the locale on https://docs.python.org/3/library/locale.html . And - in order to complete the answer - if the program is to be "internationalized" only locale is not enough - it is necessary to use a framework that allows the translation of all strings that go to the program interface. The locale module only takes care of the formatting of numbers and name of months and days of the week. For translations, it is necessary to use the gettext library: https://docs.python.org/3/library/gettext.html

2

That way the new Neoroficaria without the point and with the comma in its place

 numero = input('Entre com o numero : ')
 novoNumero = numero.replace(".",",")
  • It is worth remembering that raw_input is a function of Python 2, while Python 3 uses only input.

  • @Andersoncarloswoss yes but I did it just for examples, but good addition, I will edit

Browser other questions tagged

You are not signed in. Login or sign up in order to post.