如何在 Python 中獲取一個以空格填充的字串,並使原始字串右對齊?


字串是一系列字元,可以表示單個單詞或完整的短語。在 Python 中,我們可以在沒有資料型別說明符的情況下宣告字串或任何其他資料型別。因此,與 Java 相比,在 Python 中使用字串更容易。

Python 中的字串由名為 String 的類表示。此類提供多個函式和方法,您可以使用這些函式和方法對字串執行各種操作。

在本文中,我們將重點介紹如何在 Python 中獲取一個以空格填充的字串,並使原始字串右對齊。

使用 rjust() 方法

Python 的 rjust() 方法用於將字串與指定數量的位置右對齊。以下是此函式的語法:

string.rjust(length, character)

其中,

  • length 是您想要填充的空格數(此數字包含字串的長度;如果數字小於字串的長度,則不會進行任何更改)。

  • character 是一個可選引數,用於使用指定的字元填充空格(如果未指定字元,則會填充空格)。

示例 1

在下面給出的程式中,我們使用 rjust 方法用空格填充給定的字串。

str1 = "Welcome to Tutorialspoint" str2 = str1.rjust(30) print("Padding the string: ",str1) print(str2)

輸出

上述程式的輸出為:

('Padding the string: ', 'Welcome to Tutorialspoint')
     Welcome to Tutorialspoint

示例 2

在下面給出的示例中,我們使用 rjust 方法用符號“$”填充給定的字串。

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

輸出

上面給出的示例的輸出為:

('Padding the string ', 'Welcome to Tutorialspoint')
$$$$$Welcome to Tutorialspoint

示例 3

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

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

輸出

上面給出的程式的輸出為:

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

使用 format() 方法

Python 的 format() 方法是下一個選項。為了填充空白並填充字串,我們可以使用字串格式化技術。此方法通常與 print 語句一起使用。

我們將使用冒號 (:) 來指示需要填充的括號中空格的數量,以便提供正確的填充。要新增左填充,我們還應該新增 > 符號。

示例

在下面給出的示例中,我們獲取一個字串作為輸入,並使用 format 方法填充字串的左側。

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

輸出

上述程式的輸出為:

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

更新於: 2022-10-19

541 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告