Python中字符串数组问题的串联:Str(ArrayOfString[1])+&引用&引用+;Str(ArrayOfString[2])不';好像不行
嗨,我对python脚本有一个问题,我无法将它返回的两个字符串数组连接起来- SyntaxError:无法分配给函数调用 这是我的剧本:Python中字符串数组问题的串联:Str(ArrayOfString[1])+&引用&引用+;Str(ArrayOfString[2])不';好像不行,string,python-2.7,concatenation,slice,string-length,String,Python 2.7,Concatenation,Slice,String Length,嗨,我对python脚本有一个问题,我无法将它返回的两个字符串数组连接起来- SyntaxError:无法分配给函数调用 这是我的剧本: 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
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]
这就是我想做的;使行[1]字符串长度不超过16个字符
如果是,则将其放在第[2]行的开头,并将第[1]行切成16个字符
这是我第一次尝试做的-
#if len(str(row[1])>=16:
# str(row[2])=str(row[1])+" "+str(row[2])
# str(row[1])=str(row[1][0:14])
但由于它现在不起作用,所以我尝试在不测试字符串长度的情况下执行它,并且不直接将行[1]放入行[2],无论行[1]有多长
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()
我正在使用python 2.7和Windows操作系统,只需将您的第一次尝试更改为:
if len(str(row[1])) >= 16:
row[2] = str(row[1])+" "+str(row[2])
row[1] = str(row[1][0:16])
我的答案是根据@phylogenesis的评论自由改编的
更新:
上面的答案行不通,因为行是一个元组,因此它是不可变的。您需要将1和2的值分配给一些其他变量,并在进一步处理中使用这些变量
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])
一个简单的方法是:
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])
您不能为函数的结果赋值(如
str(行[1])=…
)。如果你知道它们已经是字符串,你可以简单地使用行[1]=行[1][:16]
。谢谢你的回答,我甚至没有意识到str被认为是一个函数。但我现在收到一个新错误:-------------------------------------文件“C:\Users\zachary\Desktop\StackOverFlowTest.py”,第35行,第[1]行=str(第[1][0:16]行)TypeError:“tuple”对象不支持项分配------------------------------------------我将尝试解决此问题,感谢您的帮助^tuple是不可变的(您无法修改它们的元素)。您需要创建一个新的元组并指定:row=(row[1][:16],row[1][16:][+”“+row[2])
。右括号中存在不匹配。我更新了答案,请立即尝试。是的,P已经注意到并修复了它,它现在已经过去了,但仍然不起作用,我收到了以下错误消息:--------------------------------------------------------------文件“C:\Users\zachary\Desktop\StackOverFlowTest.py”,第35行,第[1]行=str(第[1]行][0:16])TypeError:“tuple”对象不支持项分配-------------------------------------------我试图注释“row[2]=str…”行,并将“row[1]=str(row[1][0:16])”行更改为“row[1]=row[1][0:16]”,但这两种方式都不起作用是的。返回的行变量是一个元组,因此它是不可变的。它似乎起作用了。非常感谢您的帮助,我要出去吃午饭了。我没有时间详细检查结果,但从我迄今为止看到的情况来看,它起作用了,非常感谢!没问题。我很高兴这有帮助。享受:)