如何在Python中获得左填充了零的字符串?

如何在Python中获得左填充了零的字符串?

字符串是一组字符,可以表示一个单词或整个句子。在Python中,无需显式声明字符串,我们可以直接将它们分配给字面量。因此,很容易使用它们。

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

在本文中,我们将了解如何在Python中获得左填充了零的字符串。

阅读更多:Python 教程

使用rjust()函数

一种实现此目标的方法是使用名为rjust()的内置字符串函数。宽度参数是您希望填充的空格数(此数字包括字符串的长度。如果数字小于字符串的长度,则不会进行任何更改),fillchar参数是一个可选参数,用于将空隙填充为所提供的字符(如果未指定字符,则会填充空格)。要填充或填充字符串左侧的空格,请使用rjust()函数。

例1

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

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

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

输出

上述程序的输出为,

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

例2

在下面的示例中,我们使用rjust和填充符“0”填充字符串的左侧。

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

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

输出

上述程序的输出为,

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

使用format()函数

另一种选择是使用format()函数。字符串格式方法可用于填充空格并填充字符串。format()函数经常用于打印语句。

我们将使用冒号来表示必须填充的花括号中的空格数量,以便给出正确的填充。我们还应该使用>符号添加左填充。

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

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

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

输出

上述例子的输出为,

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

使用zfill()函数

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

示例

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

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

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

输出

上述示例的输出为,

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程