The*_*tor 2 python numpy function string-formatting
我在定义中使用Python的字符串格式化方法来调用一些.txt文件.一个这样的例子是:
def call_files(zcos1,zcos1,sig0):
a,b = np.loadtxt('/home/xi_'+str(zcos1)+'<zphot'+str(sig0)+'<'+str(zcos2)+'_.dat',unpack=True)
Run Code Online (Sandbox Code Playgroud)
这里str(sig0)给出了调用的地方sig0 == 0.050.然而,当我这样做,而不是采取0.050,它是四舍五入0.05!
我如何str(sig0)成为0.050代替0.05?
使用str.format()或%:
>>> "{:.03f}".format(0.05)
'0.050'
Run Code Online (Sandbox Code Playgroud)
您可以通过一次调用来格式化整个路径,str.format()如下所示:
a, b = np.loadtxt("/home/xi_{}<zphot{:.03f}<{}_.dat".format(zcos1, sig0, zcos2),
unpack=True)
Run Code Online (Sandbox Code Playgroud)
或者使用Adam Smith建议的关键字参数:
a, b = np.loadtxt("/home/xi_{cos1}<zphot{sig0:.03f}<{cos2}_dat".format(
cos1=zcos1, sig0=sig0, cos2=zcos2), unpack=True)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
235 次 |
| 最近记录: |