【问题标题】:Python - Convert currency code to its signPython - 将货币代码转换为其符号
【发布时间】:2010-12-19 13:36:48
【问题描述】:

在 Python 中,如何将货币代码转换为符号?

例如,USD 将转换为 $JPY 将转换为 ¥

如果没有通用的方法来做到这一点,网络上有没有这些的简单字典?

谢谢。

【问题讨论】:

  • 输入货币代码 - 美元、日元等
  • 请注意,许多货币本身没有符号。例如,“Kr”不是符号,它只是斯堪的纳维亚货币中使用的“Krona”的缩写。实际上,在大多数情况下,写出货币“SEK”、“NOK”、“ISK”等更适合这些。另请注意,许多符号不是唯一的。

标签: python currency


【解决方案1】:

使用locale 模块:

import locale

locales=('en_AU.utf8', 'en_BW.utf8', 'en_CA.utf8',
    'en_DK.utf8', 'en_GB.utf8', 'en_HK.utf8', 'en_IE.utf8', 'en_IN', 'en_NG',
    'en_PH.utf8', 'en_US.utf8', 'en_ZA.utf8',
    'en_ZW.utf8', 'ja_JP.utf8')
for l in locales:
    locale.setlocale(locale.LC_ALL, l)
    conv=locale.localeconv()
    print('{ics} ==> {s}'.format(ics=conv['int_curr_symbol'],
                                 s=conv['currency_symbol']))

产量:

AUD  ==> $
BWP  ==> Pu
CAD  ==> $
DKK  ==> kr
GBP  ==> £
HKD  ==> HK$
EUR  ==> €
INR  ==> ₨
NGN  ==> ₦
PHP  ==> Php
USD  ==> $
ZAR  ==> R
ZWD  ==> Z$
JPY  ==> ¥

请注意,您需要在您的机器上安装语言环境信息。在 Ubuntu 上,这意味着安装了正确的 language-pack-* 软件包。

在 *nix 系统上,您可以使用

找到已知语言环境的列表(例如 en_GB.utf8
locale -a

我不知道如何从 Python 中获取此列表(不使用 subprocess)。

【讨论】:

  • 这不做任何转换,它只是打印出一组固定语言环境的映射。
【解决方案2】:

Babel 怎么样?

from babel import numbers
print numbers.format_currency(1500, 'USD', locale='en') # => $1,500.00
print numbers.format_currency(1500, 'GBP', locale='fr_FR') # => 1 500,00 £UK

【讨论】:

  • 这会将数字格式化为货币。要将货币代码转换为符号,您可以使用 babel 的 get_currency_symbol 函数。
  • 如果要指定小数位,请传递 format=currency_digits= 参数。例如,要四舍五入到最接近的整数: : numbers.format_currency(1, 'USD', locale='en', format='#,##0.#', currency_digits=False)'1'。要启用额外的小数位:numbers.format_currency(1.2345, 'USD', locale='en', format='#,##0.00######', currency_digits=False)'1.2345'
【解决方案3】:

Forex-python 包会将货币代码转换为其符号。

>>> from forex_python.converter import CurrencyCodes
>>> c = CurrencyCodes()
>>> print c.get_symbol('GBP')
£

您可以将金额从一种货币转换为另一种货币。

>>> c= CurrencyRates()
>>> c.convert('USD', 'INR', 10)
674.73

试试看

【讨论】:

  • 这会转换USD -> US$
【解决方案4】:

使用dict

>>> currencies = {'USD': '$', 'AUD': '$', 'EUR': '€'}
>>> print currencies['USD']
$
>>> print currencies['AUD']
$
>>> print currencies['EUR']
€
>>> print currencies['GBP']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'GBP'

【讨论】:

    【解决方案5】:

    this 有帮助吗?

    此页面是在使用的符号列表 日常生活中表示一个数字 是货币价值,例如 美元符号“$”,英镑符号“£”, 和欧元符号“€”。

    重要 - 我们还保持完整的 使用的三字母代码列表 国际上区分一个 其他货币,例如“USD” 对于美元,“英镑” 英镑,以及 “EUR”代表欧元。看一个完整的 所有这些代码的列表,请参阅 我们的XE.com - ISO 4217 Type Currency Code List

    您应该能够创建一个有用的字典,将 3 字母代码映射到适当的 Unicode 货币符号。

    【讨论】:

      猜你喜欢
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      • 2014-12-07
      • 1970-01-01
      • 2021-11-03
      • 2014-12-31
      • 2011-07-07
      相关资源
      最近更新 更多