【发布时间】:2012-09-26 21:53:53
【问题描述】:
我必须将两个 Python 函数翻译成 PHP。第一个是:
def listspaces(string):
return [i -1 for i in range(len(string)) if string.startswith(' ', i-1)]
我假设这将检查提供的字符串中的空格并在找到第一次出现空格时返回 True,这是正确的吗?
这里的i-1 是什么?是-1 吗?
在 PHP 中,我们使用 [] 表示数组。这里我们是[],有返回,这个函数会返回真假还是空格位置数组?
第二个功能是
def trimcopy(copy, spaces, length=350):
try:
if len(copy) < length:
return copy
else:
loc = 0
for space in spaces:
if space < length:
loc = space
else:
return copy[:loc]
except :
return None
空格中的空格是什么:这里是return copy[:loc]
【问题讨论】:
-
检查python列表理解,for循环和python切片......
-
这些都是很奇怪的函数(尤其是
trimcopy)! -
我想出这个作为两个函数的 php 替代 list($short) = explode("\n",wordwrap($string,100));这是正确的吗?
-
这不太行,在 trimcopy 的 else 块中试试这个位: list($newtext) = explode(" ",wordwrap($string,350," "));,但是很难说出函数的意图(因为它肯定有问题)!