You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python实现与PostgreSQL(en_US.UTF-8排序)一致的字符串排序?

让Python字符串排序与PostgreSQL(en_US.UTF-8规则)对齐

问题场景

你的PostgreSQL数据库使用en_US.UTF-8排序规则:

# SHOW lc_collate;
 lc_collate  
-------------
 en_US.UTF-8

但Python与PostgreSQL对同一字符串列表的排序结果不一致:

  • Python默认排序输出:
sorted(['C - test', 'Common Scope'])
['C - test', 'Common Scope']
  • PostgreSQL默认排序输出:
# select * from TEST ORDER BY name;
     name      
--------------
 Common Scope
 C - test

已知在PostgreSQL查询中添加COLLATE "C"可让其排序结果与Python一致,现在需要让Python的排序逻辑匹配PostgreSQL的en_US.UTF-8规则。

解决方案

可以通过Python的locale模块实现,利用指定区域的排序规则进行字符串排序:

实现代码

import locale

# 设置排序使用的区域为en_US.UTF-8
locale.setlocale(locale.LC_COLLATE, 'en_US.UTF-8')

# 用locale.strxfrm作为排序key,遵循en_US.UTF-8规则排序
sorted_list = sorted(['C - test', 'Common Scope'], key=locale.strxfrm)
print(sorted_list)
# 输出结果:['Common Scope', 'C - test']

注意事项

  • 不同操作系统的区域名称可能有差异:比如Windows系统可能需要使用'English_US.UTF-8'作为区域参数,若设置失败可查询对应系统的正确区域标识
  • 若要恢复Python默认排序规则,可执行locale.setlocale(locale.LC_COLLATE, '')

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 10:10:49