Search code examples
pythonprintingpyramid

Python: Issue with string concatenation


I am trying to construct something sort of sum pyramid in my code, but I am not able to print anything after the end= ( in python 2.7)

from __future__ import print_function
import time

YEAR_STR= time.strftime('%Y')
MONTH_STR=time.strftime('%m')

num = 1
for i in range(0, 5):
    num = 1
    for j in range(0, i+1):
        print("(ABC_"+YEAR_STR+MONTH_STR+str(num), end="+")
        num = num + 1
    print()

The output I get is :

(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 the expected output is :

(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 so on ....

I am not able to add the last )/num in the print statement. Can this be done?


Solution

  • You can do it by yourself like this:

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

      import time
      
      YEAR_STR= time.strftime('%Y')
      MONTH_STR=time.strftime('%m')
      
      
      for i in range(0, 5):
        num = 0
        tmp = ""  
        for 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