以下函数是尝试反转字符串。 代码引发异常
'str' object does not support item assignment
错误。
代码
text =''
def reverse(text):
r=text
m=len(text)-1
for i in (r):
r[m]=i
m-=1
return sum(r)
答案 0 :(得分:1)
例外原因 出错的原因是python字符串是不可变的
逻辑问题 即使在可变列表类型上,代码也不会起作用。代码有几个逻辑错误
详细解决方案
string在python中是不可变的,你不能使用
r[index]= value
以上代码无效
反向你可以做
def reverse(text):
return text[::-1]
最佳解决方案
如果slicing
或reversed
更好,那么值得争论。因为reversed
返回迭代器
以下是使用ipython
进行的比较In [13]: %timeit "sarath"[::-1]
The slowest run took 14.82 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 257 ns per loop
In [14]: %timeit "".join(reversed("sarath"))
The slowest run took 9.02 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 1.32 µs per loop