printing - Python: Issue with string concatenation -


i trying construct sort of sum pyramid in code, not able print after end= ( in python 2.7)

from __future__ import print_function import time  year_str= time.strftime('%y') month_str=time.strftime('%m')  num = 1 in range(0, 5):     num = 1     j in range(0, i+1):         print("(abc_"+year_str+month_str+str(num), end="+")         num = num + 1     print() 

the output :

(abc_2017031+ (abc_2017031+(abc_2017032+ (abc_2017031+(abc_2017032+(abc_2017033+ (abc_2017031+(abc_2017032+(abc_2017033+(abc_2017034+ (abc_2017031+(abc_2017032+(abc_2017033+(abc_2017034+(abc_2017035+ 

but expected output :

(abc_2017031)/1 (abc_2017031+abc_2017032)/2 (abc_2017031+abc_2017032+abc_2017033)/3 (abc_2017031+abc_2017032+abc_2017033+abc_2017034)4 

and on ....

i not able add last )/num in print statement. can done?

you can this:

  • you concatenate the output in temporary variable
  • you adding '+' if it's not last character in line being printed

    import time  year_str= time.strftime('%y') month_str=time.strftime('%m')   in range(0, 5):   num = 0   tmp = ""     j in range(0, i+1):     num = num + 1       tmp += "abc_"+year_str+month_str+str(num)     if (j < i):       tmp+="+"    print("(%s)/%d"% (tmp, num)) 

output:

(abc_2017031)/1 (abc_2017031+abc_2017032)/2 (abc_2017031+abc_2017032+abc_2017033)/3 (abc_2017031+abc_2017032+abc_2017033+abc_2017034)/4 (abc_2017031+abc_2017032+abc_2017033+abc_2017034+abc_2017035)/5 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -