我必须把两个Python函数翻译成PHP。第一个是:
def listspaces(string):
return [i -1 for i in range(len(string)) if string.startswith(' ', i-1)]
我假设这将检查提供的字符串中的空格,并在第一次找到空格时返回True,这是正确的吗?在
这里i-1
是什么?是-1
?在
在PHP中,我们使用[]
作为数组。这里是[]
返回,这个函数将返回true或false或空格位置数组吗?在
第二个功能是
^{pr2}$空间中的空间是什么:这里和这是什么return copy[:loc]
为什么不测试这些函数看看它们在做什么呢?在
listspaces(string)
返回一个数组,其中包含字符串中所有空格的位置:(
i -1
是空间从零开始计数时的位置)我对Python不太了解,也不能粘贴第二个函数,因为有很多“IndentationError”
我认为
trimcopy()
将返回一个字符串(来自输入copy
),其中数组spaces
(显然是来自listspaces()
的返回值)后面的所有内容都将被修剪,除非输入的长度不超过length
。 换句话说:输入在小于length
的最高空间位置被切断。在如上例,部件
^{pr2}$' Welt!'
将被切断:我认为这类转换的一个好方法是:
找出代码的作用
用Python将其重构为PHP样式(这使您能够检查逻辑是否仍然有效,例如使用断言测试)。e、 g.将列表理解转换为for循环
转换为PHP
例如,
listspaces(string)
返回string
中空格的位置,尽管使用列表理解是python的,但它不是很“PHP-onic”。在第二个例子,
trimcopy
相当棘手(因为这个尝试,除了有目的地捕捉到一些预期的-对作者来说(!)-例外情况-有两种可能是string
没有len
和spaces
包含的值长于len(copy)
),但很难说,所以在Python中重构和测试是个好主意。在您可以使用^{} 在PHP中像
copy[:loc]
那样执行数组切片。在注意:通常在Python中,我们会显式地声明我们要防御的异常(与Pokemon exception handling相反)。
您可能会注意到第一个函数也可以写成
该版本可以直接转换为PHP:
^{pr2}$至于另一个函数,这似乎在几乎相同的习语中起着相同的作用:
正如其他人所指出的,使用
wordwrap
可以更好地表达这两个函数的意图。在相关问题 更多 >
编程相关推荐