为什么这段代码会反向转换字符串,每行代码到底是做什么的?

时间:2019-06-07 00:53:50

标签: python python-3.x

对于python来说是相当新的东西,因此该字符串对我来说只有一半的意义,有人可以向我解释这段代码中发生了什么

def rev(st):
    s = ""
    for ch in st:
        s = ch + s
    return s

print(rev("hello"))

3 个答案:

答案 0 :(得分:0)

s = "bc"
ch = "a"
ch + s = "a" + "bc" = "abc"

for循环仅遍历字符串,并将此函数应用于遇到的每个通道。

答案 1 :(得分:0)

当“求和”字符串时,变量的顺序很重要。

'a' + 's' != 's' + 'a'
'a' + 's' = 'as'
's' + 'a' = 'sa'

循环中发生的事情是您将每个字母分配给空字符串的左侧。

Iteration one: ch + s = 'h' + '' -> 'h'
Iteration two: ch + s = 'e' + 'h' -> 'eh'
etc

答案 2 :(得分:0)

我知道python3也是这样的

  

def reverse(str):       返回(str [::-1])   print(reverse(“ hello”))

这个对我来说很清楚。

但是我对上面的工作方式很感兴趣