我想创建一个函数,以返回反转的文本。 这里的问题是,“ x”不存储我不知道为什么的倒排文本。
这就是代码
def text_inverted(w):
for i in range(len(w)-1,-1,-1):
x=""
x+=w[i]
return x
print(text_inverted("hello"))
答案 0 :(得分:2)
将x
移动到for循环之外,因为当前您每次在for循环迭代时都会重置x:
def text_inverted(w):
x = ""
for i in range(len(w)-1,-1,-1):
x+=w[i]
return x
print(text_inverted("hello")) #prints olleh
解决此问题的另一种方法是使用Python的切片概念:
def text_inverted(w):
return w[::-1]
print(text_inverted("hello"))
答案 1 :(得分:2)
问题是您在x
循环的每次迭代中将for
重新分配为空字符串。将语句x = ''
移到循环上方,您的函数应该可以正常工作。
演示:
>>> def text_inverted(w):
... x = ''
... for i in range(len(w)-1,-1,-1):
... x += w[i]
... return x
...
>>>
>>> print(text_inverted("hello"))
olleh
顺便说一句,反转字符串的惯用方式使用切片符号。
>>> 'hello'[::-1]
'olleh'
答案 2 :(得分:2)
有更简单的方法。
a="hello"
print(a[::-1])
答案 3 :(得分:1)
问题在于,您需要在循环的每次迭代中完全重置x
的值。
def inverted(w):
i = 0;
x = '';
length = len(w);
while i < length:
x += w[length - 1];
length = length - 1;
return x;
print(inverted('hello'));
答案 4 :(得分:0)
如其他答案所述,您不应在for循环内设置变量x
;只是在它外面初始化。
一个更好,更简单的替代方法是使用Python内置解决方案:
w[::-1]
它将返回反向的w
字符串。