Python 字串 zfill() 方法



Python 字串 zfill() 方法用於在字串左側填充零,直到達到指定的寬度;也稱為填充。如果此字串的字首是符號字元(+ 或 -),則零將新增到符號字元之後,而不是之前。

如果字串的長度大於填充後的字串總寬度,則 Python 字串 zfill() 方法不會填充字串。

注意:如果我們將 fillchar 引數設定為 '0',則 zfill() 方法的工作原理類似於 rjust() 方法。

語法

以下是 Python 字串 zfill() 方法的語法:

str.zfill(width)

引數

  • width - 這是字串的最終寬度。這是填充零後得到的寬度。

返回值

此方法返回填充後的字串。

示例

如果我們將 zfill() 方法應用於輸入字串,則填充零的字串將作為結果獲得。

以下示例演示了 Python 字串 zfill() 方法的使用。在這裡,我們將字串 "this is string example....wow!!!" 作為輸入,並對其呼叫兩次 zfill() 方法,引數分別為 '40' 和 '50'。每種情況下,返回值都將是具有前導零的字串,直到指定的寬度。

str = "this is string example....wow!!!";
print(str.zfill(40))
print(str.zfill(50))

執行上述程式時,會產生以下結果:

00000000this is string example....wow!!!
000000000000000000this is string example....wow!!!

示例

如果 zfill() 方法的 width 引數小於字串長度,則返回原始字串作為結果。

在以下示例中,我們建立一個字串,例如 "Welcome to Tutorialspoint",並在此字串上呼叫 zfill() 方法。輸入字串為

str = "Welcome to Tutorialspoint";
print(str.zfill(20))

執行上述程式時,會產生以下結果:

Welcome to Tutorialspoint

示例

如果我們建立一個包含日期的字串作為輸入,則呼叫 zfill() 方法以將字串返回為標準日期格式(以 DD-MM-YYYY 格式)。

在此示例中,我們建立了三個輸入字串:day、month 和 year,它們連線在一起時不遵循標準日期格式(DD/MM/YYYY)。因此,我們對每個字串呼叫 zfill() 方法,在必要時新增前導零,並以正確的格式獲取日期。結果字串將列印為輸出。

def perfect_date(day, month, year):
   day = day.zfill(2)
   month = month.zfill(2)
   year = year.zfill(4)
   date = day + '/' + month + '/' + year
  print("The perfect date (DD-MM-YYYY) is: " + date)

day = '2'
month = '6'
year = '2022'
perfect_date(day, month, year)

上述程式的輸出顯示如下:

The perfect date (DD-MM-YYYY) is: 02/06/2022
python_strings.htm
廣告