在字符方式交换两个字符串时出错...
代码:
#Exchange names using 2-D array of characters
names=["akshay","parag","raman","srinivas","gopal","rajesh"]
print "Original:%s %s\n" % (names[2],names[3])
for i in range(0,10,1):
t=names[2][i]
names[2][i]=names[3][i]
names[3][i]=t
print "New:%s %s\n" % (names[2],names[3])
TypeError: 'str' object does not support item assignment
任何解决方案?
答案 0 :(得分:1)
names
是一个字符串列表。因此,当您执行names[2][someIndex]
时,您正在访问该字符串的单个字符。所以当你names[2][i] = names[3][i]
时,你试图交换两个字符。因为Python字符串是不可变的,所以这不起作用。
除此之外,您还尝试访问不存在的该字符串的索引。例如,names[2]
为raman
,因此长度为5个字符。由于您将i
循环到9
,因此您最终会尝试访问'raman'[5]
,'raman'[6]
,...,'raman'[9]
这些都会引发IndexError。< / p>
如果要在列表中交换两个字符串,只需将字符串作为一个整体进行交换:
>>> names = ["akshay","parag","raman","srinivas","gopal","rajesh"]
>>> t = names[2]
>>> names[2] = names[3]
>>> names[3] = t
或者简而言之,没有临时变量:
>>> names[2], names[3] = names[3], names[2]
答案 1 :(得分:0)
字符串在Python中是不可变的,您可以在这里使用bytearray
:
names = map(bytearray, names)
print "Original:%s %s\n" % (names[2],names[3])
for i in range(10):
try:
#That's how we swap items in Python.
names[2][i], names[3][i] = names[3][i], names[2][i]
except IndexError:
#'raman' will raise error for index 5, so we need to catch that here
#Do someting here for unequal strings or break
break
print "New:%s %s\n" % (names[2],names[3])
您无法更新字符串,您可以使用字符串方法或切片等创建新字符串。
<强>更新强>
names = map(bytearray, names)
print "Original:%s %s\n" % (names[2],names[3])
s = sorted((names[2], names[3]), key=len)
for i in range(len(s[1])):
try:
# Here in case of unequal length string, s[0] is the shorter string
# and s[1] is the longer one.
s[0][i], s[1][i] = s[1][i], s[0][i]
except IndexError:
for _ in range(i, len(s[1])):
#remove the items from the longer string and append them to the shorter one.
s[0].append(s[1].pop(i))
print "New:%s %s\n" % (names[2],names[3])
另请注意,bytearray
只有在使用ASCII字符时才可以使用,不要将其与非ASCII数据一起使用。
答案 2 :(得分:0)
这会正确地将names[2]
和names[3]
换成一行:
names[2], names[3] = names[3], names[2] # they are swapped - a,b = b,a
答案 3 :(得分:0)
如果你的每个字符串至少有10个字符,你可以完全没有循环:
names[2], names[3] = names[3][:10] + names[2][10:], names[2][:10] + names[3][10:]
这可以同时完成两项任务。在此之后,names[2]
将包含names[3]
的前10个字母和位置10的names[2]
字母。同样适用于names[3]
。