如何使用 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.