如何用空格填充Python字串?
字串是由字元組成的集合,可以表示單個單詞或整個句子。與其他技術不同,Python 中不需要顯式宣告字串,我們可以有或沒有資料型別說明符來定義字串。
Python 中的字串是 String 類的物件,其中包含多個方法,可以使用這些方法來操作和訪問字串。
在本文中,我們將討論如何用空格填充 Python 字串。讓我們逐一檢視各種解決方案。
使用 ljust()、rjust() 和 center() 方法
為了用所需的字元填充字串,Python 提供了三種方法:ljust()、rjust() 和 center()。
ljust() 函式用於在給定字串的右側填充空格。
rjust() 函式用於在給定字串的左側填充空格。
center() 函式用於在字串的左右兩側填充空格。
所有這些方法都有兩個引數:
width - 表示要填充的空格數。此數字包括字串的長度,如果此數字小於字串的長度,則不會有任何更改。
fillchar(可選) - 此引數表示要作為填充使用的字元。如果沒有指定,則給定字串將用空格填充。
示例 1
在下面給出的程式中,我們首先使用ljust()方法進行填充,然後使用@進行填充。
str1 = "Welcome to Tutorialspoint" str2 = str1.rjust(15) #str3 = str1.ljust(15,'@') print("Padding the string ",str1) print(str2) print("Filling the spaces of the string",str1) print(str1.rjust(15,'@'))
輸出
上述程式的輸出為:
('Padding the string ', 'Welcome to Tutorialspoint')
Welcome to Tutorialspoint
('Filling the spaces of the string', 'Welcome to Tutorialspoint')
Welcome to Tutorialspoint
示例 2
在下面給出的程式中,我們首先使用rjust()方法進行填充,然後使用@進行填充。
str1 = "Welcome to Tutorialspoint" str2 = str1.rjust(30) str3 = str1.rjust(30,'@') print("Padding the string ",str1) print(str2) print("Filling the spaces of the string",str1) print(str3)
輸出
上述程式的輸出為:
('Padding the string ', 'Welcome to Tutorialspoint')
Welcome to Tutorialspoint
('Filling the spaces of the string', 'Welcome to Tutorialspoint')
@@@@@Welcome to Tutorialspoint
示例 3
在下面給出的程式中,我們首先使用center()方法進行填充,然後使用@進行填充。
str1 = "Welcome to Tutorialspoint" str2 = str1.center(30) str3 = str1.center(30,'@') print("Padding the string ",str1) print(str2) print("Filling the spaces of the string",str1) print(str3)
輸出
上述程式的輸出為:
('Padding the string ', 'Welcome to Tutorialspoint')
Welcome to Tutorialspoint
('Filling the spaces of the string', 'Welcome to Tutorialspoint')
@@Welcome to Tutorialspoint@@@
使用 format() 方法
我們可以使用字串 format 方法來填充空格和字串填充。我們主要在 print 語句上執行 format() 函式。
我們將在花括號中提到要填充的空格數,使用冒號新增右側填充。要新增左側填充,我們還應該新增 > 符號,對於居中填充,我們應該使用 ^ 運算子。
對於右填充,使用以下語句:
print('{:numofspaces}'.format(string))
對於左填充,使用以下語句:
print('{:>numofspaces}'.format(string))
對於居中填充,使用以下語句:
print('{:^numofspaces}'.format(string))
示例
在下面給出的示例中,我們使用 format 方法進行右填充、左填充和居中填充。
str1 = "Welcome to Tutorialspoint" str2 = ('{:35}'.format(str1)) str3 = ('{:>35}'.format(str1)) str4 = ('{:^35}'.format(str1)) print("Right Padding of the string ",str1) print(str2) print("Left Padding of the string ",str1) print(str3) print("Center Padding of the string ",str1) print(str4)
輸出
上述程式的輸出為:
('Right Padding of the string ', 'Welcome to Tutorialspoint')
Welcome to Tutorialspoint
('Left Padding of the string ', 'Welcome to Tutorialspoint')
Welcome to Tutorialspoint
('Center Padding of the string ', 'Welcome to Tutorialspoint')
Welcome to Tutorialspoint
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP