在 Python 字符串中添加尾随零
作为数据处理活动的一部分,我们有时需要将一个字符串附加到另一个字符串。在本文中,我们将了解如何将动态数量的零附加到给定的字符串。这可以通过使用各种字符串函数来完成,如下面的程序所示。
使用 ljust 和 len
Python 字符串方法 ljust() 返回在长度为 width 的字符串中左对齐的字符串。填充使用指定的 fillchar 进行(默认为空格)。len() 返回字符串的长度。我们通过操作给定字符串的长度和 ljust 函数来添加尾随零。
示例
#Add trailing Zeros to a Python string
# initializing string
str = 'Jan-'
print("The given input : " + str(str))
# No. of zeros required
n = 3
# using ljust() adding trailing zero
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 的字符串,并使用 format 方法添加两个尾随零。
示例
str= 'Spring:'
print("\nThe given input : " + str(str))
# using format()adding trailing zero n for number of elememts, '0' for Zero, and '<' for trailing
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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP