將前導零新增到 Python 字串
有時候,我們可能需要將零作為字串附加到 Python 中的各種資料元素。這樣做可能是為了格式化和美觀顯示,也可能是為了某些將這些值作為輸入的計算。以下是我們將用於此目的的方法。
使用 format()
這裡我們獲取一個 DataFrame 並將 format 函式應用於需要將零附加為字串的列。lambda 方法用於重複應用函式。
示例
import pandas as pd
string = {'Column' : ['HOPE','FOR','THE','BEST']}
dataframe=pd.DataFrame(string)
print("given column is ")
print(dataframe)
dataframe['Column']=dataframe['Column'].apply(lambda i: '{0:0>10}'.format(i))
print("\n leading zeros is")
print(dataframe)輸出
執行以上程式碼將產生以下結果 −
given column is Column 0 HOPE 1 FOR 2 THE 3 BEST leading zeros is Column 0 000000HOPE 1 0000000FOR 2 0000000THE 3 000000BEST
使用 rjust
right justify 函式透過使用我們提供給 rjust 函式的引數來幫助將給定值右對齊。在此示例中,我們使用 rjust 函式向值新增三個零。新增的零的數量可以是動態的。
示例
val = '98.6 is normal body temperature'
print("The given string is :\n " + str(val))
#Number of zeros to be added
i = 3
result = val.rjust(i + len(val), '0')
print("adding leading zeros to the string is :\n" + str(result))輸出
執行以上程式碼將產生以下結果 −
The given string is : 98.6 is normal body temperature adding leading zeros to the string is : 00098.6 is normal body temperature
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP