我从一个关于在python中反转字符串的相关问题中找到了这段代码,但有人能用通俗的英语解释它吗?请注意,我对python还是个新手,昨天才学会如何使用while循环和函数:/所以我自己还不能用语言表达,因为我的理解还不完全到位。
不管怎样,这是代码:
def reverse_string(string):
new_strings = []
index = len(string)
while index:
index -= 1
new_strings.append(string[index])
return ''.join(new_strings)
print(reverse_string('hello'))
当然,通过了解它的作用,您可以计算出代码。在while
循环中,index
值从字符串的末尾开始,并向下计数到0。在每一步中,它都会将该字符(同样,从末尾开始(添加到正在构建的列表的末尾。最后,它将列表组合成一个字符串。
因此,给定"abcd",列表就会建立起来:
'abcd' #3 -> ['d']
'abcd' #2 -> ['d','c']
'abcd' #1 -> ['d','c','b']
'abcd' #0 -> ['d','c','b','a']
基本上,用len
方法获取字符串的长度。它将返回一个表示字符串长度的整数值。
然后,他们使用这个字符串的长度,并在while
循环中有效地向下迭代到零。使用-=
运算符。
每次迭代(意味着循环中的每一次(,它都会从长度中减去,直到达到零。
因此,让我们使用hello
作为示例输入,并一起进行。
reverse_string('hello')
是我们调用该方法的方式,在代码的print
语句中完成。
然后,我们进入功能并执行以下步骤:
- 我们创建了一个名为
new_strings
的新空数组 - 我们找到初始字符串CCD_ 10的长度,它返回5。这意味着现在CCD_ 11等于5
- 我们创建了一个while循环,它一直持续到
index
不再使用while(index):
——像这样的while循环将0
值视为falsy
,并在达到该值时终止。因此,当index
是0
时,循环将停止 - 这个循环的第一行执行
index -= 1
,这与写入index = index - 1
相同,所以第一个循环通过我们得到index = 5 - 1
,然后现在index
等于4
- 因为Python允许我们使用
string[index]
访问字符串的character
(并且因为这是从0->n开始的(,所以执行hello[4]
实际上会给我们提供字符o
- 我们还将这个字符附加到数组
new_strings
,这意味着当我们通过迭代达到零时,它将把每个字符向后添加到这个数组中,从而得到['o', 'l', 'l', 'e', 'h']
- 由于索引现在为零,我们离开循环,对数组执行
join
操作,再次创建字符串。命令''.join(new_strings)
表示我们希望加入以前没有分隔符的数组。如果我们做了'#'.join(new_strings)
,我们会得到o#l#l#e#h
而不是olleh
我希望这个答案能让你明白一些。
当然,这是一个非常简单的程序。您应该在python中重新定义字符串方法和字符串索引以获得清晰的想法。让我详细解释一下。
print(reverse_string('hello'((//print函数正在调用另一个函数reverse_ string和传递参数";你好";。
defreverse_string(字符串(://参数"你好";存储在变量中reverse_string函数中的字符串。
**new_strings = []** // created a new empty list
**index = len(string)** // len function returns the length of the argument
passed to the function. len("hello")=5 and assigned
to index. index=5.
while index://while循环存在,直到条件变为false例如,当index=0时,字符串中的索引从0开始。对于实例string[0]=h,string[1]=e,string[2]=l,string[3]=l,string[4]=o。
**index -= 1** //Note the last letter 'o' is in string[4] and the len
function returned 5 so we need to decrement index variable
to 4 so that it will pointing to string[4]=o
new_strings.append(string[index](//append string[4]即o,依此类推。。。return''.join(new_strings(