在不使用方法或切片的情况下反转 python 中的字符串
reversing a string in python without using methods or slicing
此函数尝试反转提供的字符串。
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'
看不懂。有人解决吗?
您需要指定 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]
>>> s1 = 'foo'
>>> s2 = ''
>>> for i in range(len(s1)):
s2 += s1[len(s1)-i-1]
>>> s2
'oof'
当然这比效率低得多:
>>> s1[::-1]
'oof'
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))
#Reversing a string without using s[::-1]
str = "ecnalubma"
count = -8
while count <= 0:
print(str[-count], end='')
count += 1
此函数尝试反转提供的字符串。
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'
看不懂。有人解决吗?
您需要指定 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]
>>> s1 = 'foo'
>>> s2 = ''
>>> for i in range(len(s1)):
s2 += s1[len(s1)-i-1]
>>> s2
'oof'
当然这比效率低得多:
>>> s1[::-1]
'oof'
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))
#Reversing a string without using s[::-1]
str = "ecnalubma"
count = -8
while count <= 0:
print(str[-count], end='')
count += 1