Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Selected Reading

Python locale.strcoll() Function



The Python locale.strcoll() function is used to compare two strings according to the current locale settings. This function provides locale-aware string comparisons, which are essential for sorting and ordering strings in a way that respects linguistic rules.

It is particularly useful when working with internationalized applications that require proper collation of strings.

Syntax

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

locale.strcoll(string1, string2)

Parameters

This function accepts the following parameters −

  • string1: The first string to be compared.
  • string2: The second string to be compared.

Return Value

This function returns −

  • A negative value if string1 is less than string2 in the current locale.
  • Zero if both strings are equal.
  • A positive value if string1 is greater than string2 in the current locale.

Example 1

Following is an example of the Python locale.strcoll() function. Here, we compare two strings in the default locale −

import locale

locale.setlocale(locale.LC_ALL, '')
result = locale.strcoll("apple", "banana")
print("Comparison Result:", result)

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

Comparison Result: -1

Example 2

Here, we compare two strings using different locale settings to observe how collation differs −

import locale

locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
result1 = locale.strcoll("straße", "strasse")
print("German locale comparison:", result1)

locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
result2 = locale.strcoll("straße", "strasse")
print("English locale comparison:", result2)

The result produced is as follows (output may vary based on system configuration) −

German locale comparison: 0
English locale comparison: 0

Example 3

Now, we are using the locale.strcoll() function for sorting a list of words in a locale-aware manner −

import locale

words = ["zebra", "apple", "Österreich", "Banana"]
locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
sorted_words = sorted(words, key=locale.strxfrm)
print("Sorted words:", sorted_words)

The output reflects proper collation according to the German locale.

Sorted words: ['apple', 'Banana', 'Österreich', 'zebra']

Example 4

In here, we use the locale.strcoll() function to implement a custom sorting function −

import locale

words = ["café", "caffè", "coffee"]
locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
words.sort(key=locale.strxfrm)
print("French sorted words:", words)

The result ensures that sorting is performed according to French language conventions.

French sorted words: ['café', 'caffè', 'coffee']
python_modules.htm
Advertisements