2

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?

3
  • Do you mean that your variables will always be single character alphabet from A to Z max ? Commented Sep 9, 2015 at 11:38
  • net necessarily, the variable names may vary Commented Sep 9, 2015 at 11:40
  • Where are the variables defined? Are they within a function? Not that I recommend it, but could you hack something together with locals()? Commented Sep 9, 2015 at 11:48

5 Answers 5

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

its more manual than mine. The given values are separated by variable names and not in the dictionary form
Well, I don't think it's possible to automate it in any way without grouping the variables somehow. You need to specify how to access the list of variables.
What order do the values come out?
It is true you should use an OrderedDict. Not sure if I should edit my answer to reflect that, cos I would feel like stealing from you, but perhaps I should for it to be correct.
@ralh Go ahead and edit your answer if you like. Not stealing, just make your answer the best you think you can. No shame in that (c:
1

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.

3 Comments

This is shorter but it doesn't really answer the question. You still need to hand code the variable names into the format string.
@mhawke But you no longer need to add + str(var) + for each one, which I believe is the OP's concern.
Yeah, I'm not really sure what the main concern is... I think that OP is after something that will automate the insertion of the variable names into the output string too.
1

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()))

1 Comment

If you use kwargs, your ordering is lost.
0

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

Comments

-1
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.

4 Comments

eval can cause some serious issues if not used carefully.
@SuperBiasedMan i am using this code zipping the names and values without using eval
Don't use eval when you have propper substitute - globals()[varname] (or, sufficient enough in this example, locals).
Thanks all for the comments, I've edited my answer to use locals().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.