Reputation: 480
I have to write one string as follows:
A = 55
B = 45
res = 'A =' + str(A) + '\n' + \
'B = ' + str(B)
The A and B have to be separated into two lines.
print res
Result is correct. However, if i have other variables such as C,D,E, etc. doing one by one as in my code is difficult. What is shorter and easier way for doing it?
Upvotes: 2
Views: 149
Reputation: 6284
A = 45
B = 55
C = 65
names = ['A', 'B', 'C'] # list of variable names
res = '\n'.join([varname + ' =' + str(locals()[varname]) for varname in names])
This does what you've asked for, but if it's going to be used in a practical program I would look at other methods for storing and retrieving the data such as a dictionary.
Upvotes: -1
Reputation: 8992
If you want to process all your variables (e.g. you are in function) you can use locals
def f():
A = 55
B = 45
C = 35
D = 25
print("\n".join("{} = {}".format(k, v) for k,v in locals().items()))
in action:
>>> f()
A = 55
B = 45
C = 35
D = 25
Otherwise we have to know which variables do you want to process - for example, use OrderedDict
:
d = OrderedDict([
("A", 55),
("B", 45),
("C", 35),
("D", 25),
])
print("\n".join("{} = {}".format(k, v) for k,v in d.items()))
Upvotes: 1
Reputation: 2594
You could make a dictionary of the values and iterate over it:
values = {
'A': 56,
'B': 32,
'C': 34
}
res = ''
for key in values:
res += key + ' = ' + str(values[key]) + '\n'
If you want to have the values in order, you should use an OrderedDict, as suggested in the answer by Peter Woods.
Upvotes: 2
Reputation: 1037
First of all don't start variable names from uppercase. If you want to print all values you should have more usefull data structure. Like list or dictionary.
>>> dictionary = {'a':55, 'b':45, 'c':65}
>>> for key, value in dictionary.items():
... print str(key) + ' = ' + str(value)
...
a = 55
c = 65
b = 45
If you want to have sorted output, create a list of strings first:
>>> list = []
>>> for key, value in dictionary.iteritems():
... list.append(str(key) + ' = ' + str(value))
...
>>> list
['a = 55', 'c = 65', 'b = 45']
>>> for el in sorted(list):
... print el
...
a = 55
b = 45
c = 65
Upvotes: 0
Reputation: 9979
You can use str.format
to determine res
easier:
res = 'A ={}\nB = {}'.format(A, B)
The {}
are replaced with the parameters that you pass to format
and you can pass in as many as you want.
Upvotes: 1