在不使用方法或切片的情况下在python中反转字符串

时间:2015-03-05 06:05:24

标签: python debugging

此函数尝试反转提供的字符串。

z=[]
x=range(10)
def reve(y):
    for i in range(len(y)):
        z.append(y[len-1-i])
    return z
print reve(x)

这是我得到的错误。

Traceback (most recent call last): File "C:/Users/user/Desktop/second pyth", line 40, in ? print reve(x) File "C:/Users/user/Desktop/second pyth", line 38, in reve z.append(y[len-1-i]) TypeError: unsupported operand type(s) for -: 'builtin_function_or_method' and 'int'

不能理解。解决任何人?

4 个答案:

答案 0 :(得分:2)

您需要指定ietarable的长度,即y

z.append(y[len(y)-1-i])

代码:

z=[]
x=range(10)
def reve(y):
    for i in range(len(y)):
        z.append(y[len(y)-1-i])
    return z
print reve(x)

输出:

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

答案 1 :(得分:1)

def rev(s):
    s1=""
    s2=""
    for i in range(len(s)):
        if s[i]!=" " and i!=len(s)-1:
            s1+=s[i]
        elif s[i]==" ":
            s2+=s1[::-1]+" "
            s1=""
        else:
            s1+=s[i]
            s2+=s1[::-1]
    return s2
if__name__="__main__"
s=input("Enter a sentense : ")
print("Sentence with individual reverse word : ",rev(s))

答案 2 :(得分:0)

>>> s1 = 'foo'
>>> s2 = ''
>>> for i in range(len(s1)):
        s2 += s1[len(s1)-i-1]


>>> s2
'oof'

当然,效率低于:

>>> s1[::-1]
'oof'

答案 3 :(得分:0)

#Reversing a string without using s[::-1]
str = "ecnalubma"
count = -8
while count <= 0:
    print(str[-count], end='')
    count += 1