如何使用 Python 對齊文字字串?


在本文中,我們將學習如何使用 Python 對齊文字字串。我們將使用f-字串來實現 Python 中的文字字串對齊。

Python 的文字對齊功能有助於列印格式良好且整潔的輸出。有時要列印的資料長度會有所不同,導致列印時看起來不整齊。透過指定對齊方式(左、右或居中)以及為字串保留的空間(寬度),可以使用字串對齊來對齊輸出字串。

文字將使用f-字串進行格式化。輸出字串的對齊方式由符號‘<’,‘>’,‘^’定義,後跟寬度數字。

還可以使用字串的ljust(),rjust()center()方法來對齊字串。

使用的方法

  • 使用 f-字串。

  • 使用 ljust()、rjust() 和 center() 方法

方法 1:使用 f-字串進行左對齊

左對齊輸出字串語法指定“<”,後跟寬度數字。

示例

以下程式將文字向左對齊,並保留 30 個空格 -

# 30 spaces are reserved in this case for the specific output string.
# On the left side, the string is printed.
print(f"{'The Left Aligned String!!!' : <30}")

輸出

執行上述程式後,將生成以下輸出 -

The Left Aligned String!!!

方法 2:使用 f-字串進行右對齊

右對齊輸出字串語法指定“>”,後跟寬度數字。

示例

以下程式將文字向右對齊,並保留 30 個空格 -

# 30 spaces are reserved in this case for the specific output string.
# On the right side, the string is printed.
print(f"{'The Right Aligned String!!!' : >30}")

輸出

執行上述程式後,將生成以下輸出 -

   The Right Aligned String!!!

方法 3:使用 f-字串進行居中對齊

居中對齊輸出字串語法指定“^”,後跟寬度數字。

示例

以下程式將文字居中對齊 -

# 30 spaces are reserved in this case for the specific output string.
# In the middle, the string is printed.
print(f"{'Center Aligned String!!!' : ^30}")

輸出

執行上述程式後,將生成以下輸出 -

   Center Aligned String!!!   

方法 4:以對齊格式列印變數

示例

以下程式分別使用 f-字串和 <、^、> 符號,將給定的 3 個字串以 3 種不同的對齊格式對齊 -

# input string for all the 3 types of alignments
leftAlign = "Left Alignement"
centerAlign = "Center Alignement"
rightAlign = "Right Alignement"

# printing the resultant aligned text using the <,^, > symbols 
print(f"{leftAlign : <25}{centerAlign : ^20}{rightAlign : >25}")

輸出

執行上述程式後,將生成以下輸出 -

Left Alignement           Center Alignement           Right Alignement

方法 5:以對齊的列格式列印多個列表值

示例

以下程式分別使用 f-字串和 <、^、> 符號,將給定的 4 個列表以 4 種對齊的列格式對齊 -

# input lists of multiple columns
cricketers = ['Dhoni', 'Virat Kohli',
               'Hardik Pandya', 'KL Rahul', 'Rohit Sharma']
score = [55, 90, 60, 45, 70]
place = ['Ranchi', 'Mumbai', 'Mumbai', 'Mumbai', 'Kolkata']
strikerate = [90, 60, 30, 50, 70]

# Aligning the Headers and printing them
print(f"{'Cricketers' : <20}{'Score' : ^20}{'Place' : ^20}{'Strikerate' : >10}")

# Aligning the variable values and printing them
# looping 4 times as 4 columns are using the for loop
for i in range(0, 4):
   # aligning variable values using left, center, and right alignments
   # with specific widths
   print(
      f"{cricketers[i] : <20}{score[i] : ^20}{place[i] : ^20}{strikerate[i] : >10}")

輸出

執行上述程式後,將生成以下輸出 -

Cricketers                 Score               Place        Strikerate
Dhoni                        55                Ranchi               90
Virat Kohli                  90                Mumbai               60
Hardik Pandya                60                Mumbai               30
KL Rahul                     45                Mumbai               50

方法 6:使用 ljust()、rjust() 和 center() 方法對齊文字

還可以使用字串的ljust(),rjust()center()方法來對齊字串。

ljust() 方法

使用指定的字元(預設為空格)作為填充字元,將字串左對齊。

語法

string.ljust(length, character)

引數

  • length(必需) - 返回的字串長度。

  • character(可選) - 用於填充字串右側缺失空間的字元。預設為空格(“ ”)。

rjust() 方法

使用指定的字元(預設為空格)作為填充字元,將字串右對齊。

語法

string.rjust(length, character)

引數

  • length(必需) - 返回的字串長度

  • character(可選) - 用於填充字串左側缺失空間的字元。預設為空格(“ ”)。

center() 方法

使用指定的字元(預設為空格)作為填充字元,將字串居中對齊。

語法

string.center(length, character)

引數

  • length(必需) - 返回的字串長度

  • character(可選) - 使用指定的字元填充兩側的缺失空間。預設為空格(“ ”)。

示例

以下程式分別顯示了使用 ljust()、rjust() 和 center() 方法對文字進行左、右和居中對齊 -

# input text
inputText = 'Tutorialspoint'
 
# left aligning the text of a width of 30
print("Left Alignment:", inputText.ljust(30))
 
# right aligning the text of a width of 30
print("Right Alignment:", inputText.rjust(30))
 
# center aligning the text of a width of 30
print("Center Alignment:", inputText.center(30))

輸出

執行上述程式後,將生成以下輸出 -

Left Alignment: Tutorialspoint                
Right Alignment:                 Tutorialspoint
Center Alignment:         Tutorialspoint        

方法 7:使用指定字元對齊文字

示例

以下程式分別使用 ljust()、rjust() 和 center() 方法,並使用指定的字元,顯示了文字的左、右和居中對齊 -

# input text
inputText = 'Tutorialspoint'
 
# left aligning the text of a width of 30
# fills the space with the '@' character 
print("Left Alignment:", inputText.ljust(30, '@'))
 
# right aligning the text of a width of 30
# fills the space with the '#' character 
print("Right Alignment:", inputText.rjust(30, '#'))
 
# center aligning the text of a width of 30
# fills the space with the '%' character 
print("Center Alignment:", inputText.center(30, '%'))

輸出

執行上述程式後,將生成以下輸出 -

Left Alignment: Tutorialspoint@@@@@@@@@@@@@@@@
Right Alignment: ################Tutorialspoint
Center Alignment: %%%%%%%%Tutorialspoint%%%%%%%%

結論

本文演示瞭如何使用 ljust()、rjust() 和 center() 方法在 Python 中對齊文字字串。此外,我們還學習瞭如何使用 f 字串將文字字串對齊到不同的位置。

更新於:2023年1月24日

30K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.