2

I am using Python's string formatting method inside a definition to call some .txt files. One such example is:

def call_files(zcos1,zcos1,sig0):
    a,b = np.loadtxt('/home/xi_'+str(zcos1)+'<zphot'+str(sig0)+'<'+str(zcos2)+'_.dat',unpack=True)

Here str(sig0) is given the call where sig0 == 0.050. However when I do so, instead of taking 0.050, it is rounded off to 0.05 !

How do I make str(sig0) to be 0.050 instead of 0.05 ?

Srivatsan
  • 9,225
  • 13
  • 58
  • 83

1 Answers1

5

Use str.format() or % :

>>> "{:.03f}".format(0.05)
'0.050'

You could format the whole path with a single call to str.format() like this:

a, b = np.loadtxt("/home/xi_{}<zphot{:.03f}<{}_.dat".format(zcos1, sig0, zcos2),
                  unpack=True)

or using keyword arguments as Adam Smith suggested below:

a, b = np.loadtxt("/home/xi_{cos1}<zphot{sig0:.03f}<{cos2}_dat".format(
    cos1=zcos1, sig0=sig0, cos2=zcos2), unpack=True)
Community
  • 1
  • 1
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378