Python locale.format_string() Function
The Python locale.format_string() function is used to format numbers and other values according to the current locale settings. It allows formatting of numeric values with grouping and localization applied.
This function is particularly useful for displaying numbers in a locale-aware manner, such as adding thousand separators or formatting currency values.
Syntax
Following is the syntax of the Python locale.format_string() function −
locale.format_string(format, value, grouping=False)
Parameters
This function accepts the following parameters −
- format: A format string specifying how the value should be displayed.
- value: The number or object to be formatted.
- grouping (optional): A boolean indicating whether to apply thousand separators (default is False).
Return Value
This function returns a formatted string based on the given format and locale settings.
Example 1
Following is an example of the Python locale.format_string() function. Here, we format a number with a thousand separator −
import locale
locale.setlocale(locale.LC_ALL, '')
formatted_number = locale.format_string("%d", 1000000, grouping=True)
print("Formatted Number:", formatted_number)
Following is the output of the above code (output may vary depending on the system locale) −
Formatted Number: 1,000,000
Example 2
Here, we use the locale.format_string() function to format a floating-point number with locale-aware grouping −
import locale
locale.setlocale(locale.LC_ALL, '')
formatted_float = locale.format_string("%.2f", 1234567.89, grouping=True)
print("Formatted Float:", formatted_float)
The result produced is as follows (output depends on locale settings) −
Formatted Float: 1,234,567.89
Example 3
Now, we are using the locale.format_string() function to format a currency value while applying locale-based grouping −
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
currency_value = locale.format_string("%.2f", 9876543.21, grouping=True)
print("Formatted Currency:", currency_value)
The output ensures that the number is formatted according to the en_US locale −
Formatted Currency: 9,876,543.21
Example 4
We can also use the locale.format_string() function in different locale settings to observe variations in formatting −
import locale
def format_number_in_locale(number, loc):
locale.setlocale(locale.LC_ALL, loc)
return locale.format_string("%d", number, grouping=True)
print("French locale:", format_number_in_locale(1234567, 'fr_FR.UTF-8'))
print("German locale:", format_number_in_locale(1234567, 'de_DE.UTF-8'))
The output may vary based on the locale settings, demonstrating the differences in number formatting.
French locale: 1 234 567 German locale: 1.234.567
python_modules.htm