在 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

更新於:2020年2月14日

3K+ 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.