Sasidhar_gubbala
Sasidhar_gubbala

Reputation: 59

how to pass variable values to a string in python

I have requirement where I am reading a string from json file and assign values to it to make it as a configurable file name.

String I am reading from json:

data_file_format =  "sourcesystem_batchid_extractname_loadtype"

I have variable which holds the values in my code like

sourcesystem ="xyz"
  batchid = "101"
  extractname = "abc"
  loadtype = "Delta"

so my data_file_format should yeild value like

data_file_format = "xyz_101_abc_Delta"

Upvotes: 4

Views: 15625

Answers (6)

ThunderMind
ThunderMind

Reputation: 799

There are multiple methods to do that.:

fstring

data_file_format = f'{sourcesystem}_{batchid}_{extractname}_{loadtype}'

or using .format

data_file_format = '{}_{}_{}_{}'.format(sourcetype,batchid,extractname,loadtype)

Upvotes: 7

Aman Teferi
Aman Teferi

Reputation: 1

Or you can go basic and go ahead like,

data_file_format = datasourcesystem + "_" + batchid + "_" + extractname + "_" + loadtype

The previous answer is not far off too. It just forgot the underscores

Upvotes: 0

Joyal Mathew
Joyal Mathew

Reputation: 624

.join would be the best answer in this scenario (the answer by bitto). But for the future some good methods are:

>>> a = 1
>>> b = 2
>>> c = "three"
>>> "%d and %d then %s" % (a, b, c)
1 and 2 then three
>>> "{} and {} then {}".format(a, b, c)
1 and 2 then three
>>> f"{a} and {b} then {c}"
1 and 2 then three

Upvotes: 0

ic3b3rg
ic3b3rg

Reputation: 14927

So, you need to dynamically generate a file name based on an input data_file_format. Can you store your data in a dict instead of separate variables?

data_file_format =  "sourcesystem_batchid_extractname_loadtype"

data = {
  "sourcesystem": "xyz",
  "batchid": "101",
  "extractname": "abc",
  "loadtype": "Delta"
}

filename = '_'.join([data[key] for key in data_file_format.split('_')])

print(filename)

xyz_101_abc_Delta

Upvotes: 2

Auxilus
Auxilus

Reputation: 217

you can concat strings in python with +

data_file_format =  sourcesystem + "_" + batchid + "_" + extractname + "_" + loadtype

this should give you "xyz_101_abc_Delta"

Upvotes: -1

Bitto
Bitto

Reputation: 8205

sourcesystem ="xyz"
batchid = "101"
extractname = "abc"
loadtype = "Delta"
data_file_format="_".join([sourcesystem,batchid,extractname,loadtype])
#or
#data_file_format=sourcesystem+'_'+batchid +'_'+extractname+'_'+loadtype
print(data_file_format)

Upvotes: 2

Related Questions