Hi I have a problem with a python script, I don't manage to do a concatenation of 2 arrays of strings it returns-

SyntaxError: can't assign to function call

Here's my script:

import os, sys, MySQLdb
# connecting to a database
db = MySQLdb.connect(host="localhost", user="MyUser", passwd="MyPassword",db="MyDB")

cursor = db.cursor()

cursor.execute("SELECT * FROM MyTable")

db.commit()

# get the number of rows in the resultset
numrows = int(cursor.rowcount)

# Opening a file to write in it a script
fname = os.path.normpath("C:\Users\Me\Desktop\MyScript.cmd")
f = open(fname, "w")

# get and display one row at a time.
for x in range(0,numrows):
    row = cursor.fetchone()
    print row[1], "-->", row[2]

Here is what I want to do; make row[1] String no longer than 16 char and if it is, put it in the beginning of row[2] and slice row[1] to 16 char

Here is how I first tried to do -

#if len(str(row[1])>=16:
#   str(row[2])=str(row[1])+" "+str(row[2])
#   str(row[1])=str(row[1][0:14])

But since it didn't work now I try to do it without testing the string length and directly putting row[1] in row[2] no matter how long row[1] is

    str(row[2])=str(row[1])+" "+str(row[2])
    str(row[1])=str(row[1])[:16]
    f.write("vtaddapp /Nom=test/%s /Comm=\"%s\"\n" % (str(row[1]), str(row[2])))
f.close()

I'm using python 2.7 and working with Windows OS

1

There are 1 answers

5
Vikas Ojha On BEST ANSWER

Just change your first attempt to following:

if len(str(row[1])) >= 16:
    row[2] = str(row[1])+" "+str(row[2])
    row[1] = str(row[1][0:16])

My answer is freely adapted from comment by @phylogenesis.

Update: The above answer wont work because row is a tuple and hence it is immutable. You will need to assign the values for 1 and 2 to some other variables and use those in further processing.

if len(str(row[1])) >= 16:
    temp2 = str(row[1])+" "+str(row[2])
    temp1 = str(row[1][0:16]) 
else:
    temp2 = str(row[2])
    temp1 = str(row[1])

A simple way would be:

temp2, temp1 = str(row[1])+" "+str(row[2]), str(row[1][0:16]) if len(str(row[1])) >= 16 else str(row[2]), str(row[2])