如何在 Python 中获取左侧填充零的字符串?
字符串是一组字符,可以表示单个单词或整个句子。在 Python 中,无需显式声明字符串,我们可以直接将其分配给文字。因此,易于使用它们。
字符串是 String 类的对象,它有多种方法来操作和访问字符串。
在本文中,我们将了解如何在 Python 中获取左侧填充零的字符串。
使用 rjust() 函数
实现此目标的一种方法是使用名为 rjust() 的内置字符串函数。width 参数是要填充的空间数(此数字包括字符串的长度。
如果数字小于字符串的长度,则不进行任何更改),并且 fillchar 参数是一个可选参数,它使用提供的字符填充间隙(如果未指定字符,则会填充空格)。要填充或在字符串左侧填充空格,请使用 rjust() 函数。
示例 1
在下面给出的程序中,我们使用 rjust 方法来用零对给定的字符串进行左侧填充。‘0。
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() 函数
您还可以使用 zfill() 函数在 Python 中用零对字符串进行左侧填充。我们只需要将要填充零的字符数指定为参数即可。此方法返回一个具有给定数量字符串作为输出的字符串。
示例
在下面给出的示例中,我们以字符串作为输入,并使用 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP