![](/img/trans.png)
[英]Formatting strings with numeric sequences to generate a list of strings ordered by the numbers in Python
[英]Python - Formatting items in a list of numbers to be strings with currency symbol
我有一個數字列表,這些數字是我想用符號轉換為貨幣的貨幣值:
當前列表
list = [200,4002,4555,7533]
如果我打印上面的列表,下面給出的是返回的內容:
[(Decimal('200'), Decimal('4002'), Decimal('4555'), Decimal('7533')]
預期 output
list = ['$200','$4,002','$4,555','$7,533'] <<--These are basically number formatted for 1000's separator with the currency symbol
假設您希望 output 作為字符串:
In [123]: lst = [200,4002,4555,7533]
In [124]: [f'${cur:,}' for cur in lst]
Out[124]: ['$200', '$4,002', '$4,555', '$7,533']
也不要將你的變量命名為一些內置的。
避免使用內置名稱,如變量list
。 如果不轉換為字符串,您也不能以這種格式 output ,如下所示:
l = [200, 4002, 4555, 7533]
l = ['${:0,.0f}'.format(x) for x in l]
print(l)
印刷:
['$200', '$4,002', '$4,555', '$7,533']
與其手動將列表中的值格式化為包含貨幣表示的字符串,不如使用專門用於此工作的標准庫函數。 在這里,您可能想要使用的是locale
模塊中的函數。 這些函數提供了一種方便的方法,例如以適合當前區域設置的格式表示日期、時間和貨幣。 區域設置可以由運行程序的計算機的操作系統設置,也可以由程序本身的程序員設置。
您要做的第一件事是加載locale
模塊。 然后設置區域設置,或者系統默認值:
import locale
locale.setlocale(locale.LC_ALL, "") # to use the system-wide locale setting
或您自己選擇的語言環境:
import locale
locale.setlocale(locale.LC_ALL, "en_US.utf-8") # to use the USA locale
現在,您可以使用currency
function 使用當前區域設置格式化值:
lst = [200, 4002, 4555, 7533]
cur_lst = [locale.currency(val) for val in lst]
print(cur_list)
['$200.00', '$4002.00', '$4555.00', '$7533.00']
currency
function 具有三個選項,可讓您調整 output。 grouping
選項將插入適當的分組標記以分隔數千、數百萬等:
locale.currency(123456, grouping=True)
'$123,456.00'
locale.currency(123456, grouping=False) # the default
'$123456.00'
international
選項使用國際標准貨幣縮寫而不是貨幣符號:
locale.currency(123456, international=True)
'USD 123456.00'
locale.currency(123456, international=False) # the default
'$123456.00'
最后,將symbol
選項設置為True
會完全禁止顯示貨幣符號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.