向 Python 字符串添加尾随零

pythonserver side programmingprogramming更新于 2025/6/27 10:52:17

作为数据处理活动的一部分,我们有时需要将一个字符串附加到另一个字符串。在本文中,我们将了解如何将动态数量的零附加到给定的字符串。这可以通过使用各种字符串函数来完成,如下面的程序所示。

使用 ljust 和 len

Python 字符串方法 ljust() 返回长度为 width 的字符串中左对齐的字符串。使用指定的填充字符(默认为空格)进行填充。len() 返回字符串的长度。我们通过操纵给定字符串的长度和 ljust 函数将尾随零添加到字符串中。

示例

#向 Python 字符串添加尾随零
#初始化字符串
str = 'Jan-'
print("The given input : " + str(str))
# 所需零的数量
n = 3
# 使用 ljust() 添加尾随零
output = str.ljust(n + len(str), '0')
print("adding trailing zeros to the string is : " + str(output))

输出

运行上述代码得到以下结果 −

The given input : Jan-
adding trailing zeros to the string is : Jan-000

使用 format 函数

format() 方法格式化指定的值并将其插入字符串的占位符内。占位符使用花括号定义:{}。在下面的例子中,我们取一个长度为 7 的字符串并使用格式方法添加两个尾随零。

示例

str= 'Spring:'
print("\nThe given input : " + str(str))
# 使用 format() 添加尾随零 n 表示元素数量,'0' 表示零,'<' 表示尾随
z = '{:<09}'
output = z.format(str)
print("adding trailing zeros to the string is : " + str(output))

输出

运行上述代码得到以下结果 −

The given input : Spring:
adding trailing zeros to the string is : Spring:00

相关文章


有用资源