Search code examples
pythonpython-3.xstring-concatenation

Python concatenating string statement placed on separate lines


Here is what I have tried and got the error:

a = 1
b = 2
c = 3
d = 4
e = 5

if(1):
    get = str(a) +","       #Line 1
          +str(b) +","      #Line 2
          +str(c) +","      #Line 3
          +str(d) +","      #Line 4
          +str(e)       #Line 5
else:
    get = ",,,,,"
print(get)

Error:

  File "testingpython.py", line 8
    +str(b) +","      #Line 2
    ^
IndentationError: unexpected indent

Then I try to remove the spaces:

a = 1
b = 2
c = 3
d = 4
e = 5

if(1):
    get = str(a) +","       #Line 1
+str(b) +","      #Line 2
+str(c) +","      #Line 3
+str(d) +","      #Line 4
+str(e)       #Line 5
else:
    get = ",,,,,"
print(get)

Error:

  File "testingpython.py", line 12
    else:
       ^
SyntaxError: invalid syntax

Kindly, let me know how I can assign the string values to the variable when they are placed on separate lines.


Solution

  • The simplest solution is to wrap the lines inside parethesis to indicate that they belong together:

    if(1):
        get = ( str(a) +","       #Line 1
              +str(b) +","      #Line 2
              +str(c) +","      #Line 3
              +str(d) +","      #Line 4
              +str(e)       #Line 5
        )
    else:
        get = ",,,,,"
    print(get)
    

    But you could use a shorter method:

    get = ','.join(str(s) for s in [a, b, c, d, e])