Python locale.str() Function



The Python locale.str() function is used to convert a given number to a locale-aware string representation. It ensures that numbers are formatted according to the current locale settings, including proper decimal points and thousands separators.

This function is useful for displaying numbers in a localized format without manually handling separators or decimal points.

Syntax

Following is the syntax of the Python locale.str() function −

locale.str(val)

Parameters

This function accepts a numeric value as a parameter that needs to be converted into a locale-aware string.

Return Value

This function returns a string representation of the number formatted according to the current locale settings.

Example 1

Following is an example of the Python locale.str() function. Here, we format a number based on the locale settings −

import locale locale.setlocale(locale.LC_ALL, '') formatted_number = locale.str(1234567.89) print("Formatted Number:", formatted_number)

Following is the output of the above code (output may vary depending on the system locale) −

Formatted Number: 1,234,567.89

Example 2

Here, we use the locale.str() function to convert a floating-point number to a locale-aware string representation −

import locale locale.setlocale(locale.LC_ALL, '') formatted_number = locale.str(98765.4321) print("Locale-Aware Floating Number:", formatted_number)

Output of the above code is as follows (output may vary based on system settings) −

Locale-Aware Floating Number: 98,765.4321

Example 3

Now, we use the locale.str() function to handle different locales dynamically −

import locale def display_locale_number(value): locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8') print("French Locale Format:", locale.str(value)) locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8') print("German Locale Format:", locale.str(value)) display_locale_number(12345.67)

The result obtained is as shown below (output may vary) −

French Locale Format: 12345,67
German Locale Format: 12345,67

Example 4

We can use the locale.str() function to format large numbers with thousands separators dynamically −

import locale locale.setlocale(locale.LC_ALL, '') large_number = 9876543210 formatted_number = locale.str(large_number) print("Formatted Large Number:", formatted_number)

The result produced is as follows (output may vary) −

Formatted Large Number: 9,876,543,210
python_modules.htm
Advertisements