2015-04-04 16 views
2

使用Python的str.format方法,是否有一個格式字符串只會提取數字參數的符號?Python str.format - 獲取(僅)數字的符號?

更具體地說,我需要能夠分別打印符號和數字參數的其餘部分,以便在它們之間插入一個字符。這可能是一個空格(例如,將a -4轉換爲a - 4)或自定義基本前綴(例如,對於十六進制的$-$02)。

+0

'「 - $」。join(「a -4」.split(「 - 」))'?或''-4「.replace(」 - 「,」 - $「)'? – itzMEonTV 2015-04-04 13:17:56

回答

3

不,沒有特殊的格式字符串。你必須自己編寫:

"{0}${1:02d}".format('+-'[s<0], abs(s)) 
+0

我認爲你可以使用格式字符串:) – AChampion 2015-04-04 14:22:52

+0

你是作弊,你知道它:-) – Daniel 2015-04-04 14:32:02

0

這純粹是爲了參考,深挖格式功能,您可以只用格式化做到這一點:

def myformat(n, base): 
    fill = {'d': ' ', 'x': '$'} 
    return "{:{f}=+{d}{b}}".format(n, b=base, f=fill[base], d=len(format(n, "+"+base))+1) 

>>> print(myformat(100, 'd')) 
+ 100 
>>> print(myformat(100, 'x')) 
+$64 
>>> print(myformat(-100, 'x') 
-$64 

的解釋:

n = number 
f = fill character 
= = pad after sign 
+ = show sign 
d = number of digits to pad to (number of digits of n with sign + 1 for pad char) 
b = integer base