Python 如何在字符串中填充空格
字符串是由字符组成的集合,可以表示单个单词或整个句子。与其他技术不同,Python中不需要显式声明字符串,可以使用或不使用数据类型限定符定义字符串。
在Python中,字符串是String类的对象,其中包含多个方法,可以用来操作和访问字符串。
在本文中,我们将讨论如何使用空格填充Python字符串。让我们逐个看看各种解决方案。
使用ljust(),rjust()和center()方法
为了用所需的字符填充字符串,Python提供了ljust(),rjust()和center()这三个方法。
- ljust() 函数用于在给定字符串的右侧填充空格。
-
rjust() 函数用于在给定字符串的左侧填充空格。
-
center() 函数用于在字符串的左右两侧填充空格。
所有这些方法都有2个参数:
- 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 方法来填充空格并对字符串进行填充。我们通常在打印语句上执行 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