给 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
右对齐函数可帮助我们通过使用提供给 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