Python 如何获取左侧用零填充的字符串

Python 如何获取左侧用零填充的字符串

字符串是一组字符,可以表示单词或整个句子。在Python中,不需要显式地声明字符串,我们可以直接将它们分配给文字。因此,使用它们非常方便。

字符串是String类的一个对象,该类具有多个方法来操纵和访问字符串。

在本文中,我们将找出如何在Python中获取左侧用零填充的字符串。

使用rjust()函数

实现这个目标的一种方法是使用内置的字符串函数 rjust() 。width参数是要填充的空格数量(这个数字包括字符串的长度。如果数字小于字符串的长度,就不会有任何更改),fillchar参数是一个可选参数,用于填充空格(如果没有指定字符,将以空格填充)。要在字符串左侧填充或补空格,请使用 rjust() 函数。

示例1

在下面的程序中,我们使用 rjust 方法来用零填充给定的字符串。

str1 = "Welcome to Tutorialspoint"
str2 = str1.rjust(30, '0')

print("Padding the string with zeroes ",str1)
print(str2)

输出

以上程序的输出为:

Padding the string with zeroes Welcome to Tutorialspoint
00000Welcome to Tutorialspoint

示例2

在下面给出的示例中,我们使用 rjust 函数,并用符号“0”填充字符串的左侧。

str1 = "this is a string example....wow!!!";

print(str1.rjust(50, '0'))

输出

上述程序的输出为:

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

使用format()函数

另一个选择是使用 format() 函数。字符串格式化方法可以用于填充空白和给字符串添加填充。在print语句中,经常使用 format() 函数。

我们将使用冒号表示花括号中需要填充的空白数量,还应该使用>符号添加左填充。

示例

在下面给出的示例中,我们将一个字符串作为输入,并使用format方法在字符串左侧填充零。

str1 = "Welcome to Tutorialspoint"
str2 = ('{:0>35}'.format(str1))

print("Left Padding of the string with zeroes ",str1)
print(str2)

输出

上面示例的输出为:

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

使用zfill()函数

您还可以使用Python中的 zfill() 函数用零填充一个字符串。我们只需要在参数中指定要填充零的字符数。这个方法会返回一个带有给定数量的字符串作为输出。

示例

在下面的示例中,我们输入一个字符串,并使用 zfill 方法在左侧填充零。

str1 = "Welcome to Tutorialspoint"
str2 = str1.zfill(35)

print("Left Padding of the string with zeroes ",str1)
print(str2)

输出

上述示例的输出如下:

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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程