Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python locale.getdefaultlocale() Function



The Python locale.getdefaultlocale() function is used to retrieve the default locale settings of the system. It returns a tuple containing the language code and encoding that the system is currently using.

This function is useful for determining the default locale configuration without explicitly setting it using locale.setlocale().

Syntax

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

locale.getdefaultlocale()

Parameters

This function does not accept any parameters.

Return Value

This function returns a tuple (language, encoding) where −

  • language: A string representing the language and country code (e.g., 'en_US').
  • encoding: A string representing the character encoding used by the system (e.g., 'UTF-8').

Example 1

Following is an example of the Python locale.getdefaultlocale() function. Here, we retrieve the system's default locale settings −

import locale

default_locale = locale.getdefaultlocale()
print("Default Locale:", default_locale)

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

Default Locale: ('C', 'UTF-8')

Example 2

Here, we extract and display only the language code and encoding separately −

import locale

default_locale = locale.getdefaultlocale()
language, encoding = default_locale
print("Language Code:", language)
print("Encoding:", encoding)

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

Language Code: C
Encoding: UTF-8

Example 3

Now, we use the locale.getdefaultlocale() function to handle different system locales dynamically in a program −

import locale

def set_application_language():
   language, _ = locale.getdefaultlocale()
   if language.startswith("fr"):
      print("Application language set to French.")
   elif language.startswith("de"):
      print("Application language set to German.")
   else:
      print("Application language set to English.")

set_application_language()

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

Application language set to English.

Example 4

We can use the locale.getdefaultlocale() function to check if the system supports UTF-8 encoding −

import locale

def is_utf8_supported():
   _, encoding = locale.getdefaultlocale()
   return encoding == "UTF-8"

print("UTF-8 Supported:", is_utf8_supported())

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

UTF-8 Supported: True
python_modules.htm
Advertisements