如何在 Python 中獲取左側填充零的字串?


字串是一組字元,可以表示單個單詞或整個句子。在 Python 中,無需顯式宣告字串,我們可以直接將其分配給文字。因此,易於使用它們。

字串是 String 類的物件,它有多種方法來操作和訪問字串。

在本文中,我們將瞭解如何在 Python 中獲取左側填充零的字串。

使用 rjust() 函式

實現此目標的一種方法是使用名為 rjust() 的內建字串函式。width 引數是要填充的空間數(此數字包括字串的長度。

如果數字小於字串的長度,則不進行任何更改),並且 fillchar 引數是一個可選引數,它使用提供的字元填充間隙(如果未指定字元,則會填充空格)。要填充或在字串左側填充空格,請使用 rjust() 函式。

示例 1

在下面給出的程式中,我們使用 rjust 方法來用零對給定的字串進行左側填充。‘0。

str1 = "Welcome to Tutorialspoint" str2 = str1.rjust(30, '0') print("Padding the string with zeroes ",str1) print(str2)

輸出

上面程式的輸出為:

Padding the string with zeroes Welcome to Tutorialspoint
00000Welcome to Tutorialspoint

示例 2

在下面給出的示例中,我們使用 rjust 並用符號“0”填充字串的左側

str1 = "this is a string example....wow!!!"; print(str1.rjust(50, '0'))

輸出

上面給定程式的輸出為:

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

使用 format() 函式

另一種選擇是使用 format() 函式。字串格式方法可用於填充間隙並填充字串。在 print 語句中,通常使用 format() 函式。

我們將使用冒號來指示需要填充的帶括號的間隙數,以提供正確的填充。我們還應使用 > 符號新增左側填充。

示例

在下面給出的示例中,我們以字串作為輸入,並使用 format 方法用零對字串進行左側填充。

str1 = "Welcome to Tutorialspoint" str2 = ('{:0>35}'.format(str1)) print("Left Padding of the string with zeroes ",str1) print(str2)

輸出

上面示例的輸出為:

('Left Padding of the string with zeroes ', 'Welcome to Tutorialspoint')
0000000000Welcome to Tutorialspoint

使用 zfill() 函式

您還可以使用 zfill() 函式在 Python 中用零對字串進行左側填充。我們只需要將要填充零的字元數指定為引數即可。此方法返回一個具有給定數量字串作為輸出的字串。

示例

在下面給出的示例中,我們以字串作為輸入,並使用 zfill 方法用零對字串進行左側填充

str1 = "Welcome to Tutorialspoint" str2 = str1.zfill(35) print("Left Padding of the string with zeroes ",str1) print(str2)

輸出

上面示例的輸出為:

('Left Padding of the string with zeroes ', 'Welcome to Tutorialspoint')
0000000000Welcome to Tutorialspoint

更新於: 2022-10-19

17K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告