在 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