2016-12-06 55 views
1

Python字符串有一個名爲zfill的方法,該方法允許填充左邊爲零的數字字符串。如何在Python中向零填充數字字符串?

In : str(190).zfill(8) 
Out: '00000190' 

如何讓墊子在右邊?

+0

您總是可以將字符串轉換爲整數,然後乘以10 **(num-length)並轉換回字符串。 – Douglas

回答

2

提示:字符串可以倒兩次:前和使用zfill方法之後:

In : acc = '991000' 

In : acc[::-1].zfill(9)[::-1] 
Out: '991000000' 

甚至更​​容易:

In : acc.ljust(9, '0') 
Out: '991000000' 
2

或許更便攜的[1]和高效的[2]替代方案,其實你可以使用str.ljust

In [2]: '190'.ljust(8, '0') 
Out[2]: '19000000' 

In [3]: str.ljust? 
Docstring: 
S.ljust(width[, fillchar]) -> str 

Return S left-justified in a Unicode string of length width. Padding is 
done using the specified fill character (default is a space). 
Type:  method_descriptor 

[1]格式不存在於舊的python版本。格式說明符是自Python 3.0(參見PEP 3101)和Python 2.6以來添加的。

[2]反向兩次是一個昂貴的操作。

+0

與[2] ...你的意思是雙反向速度較慢嗎? – yucer

+0

是的,雙反向速度較慢。 [2]短語有一個錯字。我的意思是*昂貴*操作,而不是*膨脹*。我會解決這個問題。 –