doukong1391 2012-09-26 11:01
浏览 275
已采纳

python到php代码转换

I have to translate two Python functions into PHP. The first one is:

def listspaces(string):
        return [i -1 for i in range(len(string)) if string.startswith(' ', i-1)]

I am assuming that this will check for space in provided string and return True when first occurrence of space is found, is this correct ?

What is i-1 here ? is it -1 ?

In PHP we use [] for arrays . Here we are [] with return, will this function return true or false or array of locations of spaces ?

Second function is

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

Whats for space in spaces: here and whats is this return copy[:loc]

  • 写回答

5条回答 默认 最新

  • dtstnjl898781429 2012-09-26 13:53
    关注

    You may notice that the first function could also have been written as

    def listspaces(str):
        return [i for i, c in enumerate(str) if c==' ']
    

    That version has the following straightforward conversion to PHP:

    function listspaces($str) {
        $spaces = array();
    
        foreach (str_split($str) as $i => $chr)
            if ($chr == ' ') $spaces[] = $i;
    
        return $spaces;
    }
    

    As for the other function, this seems to do the same thing in very nearly the same idiom:

    function trimcopy($copy, $spaces, $length=350) {
        if (strlen($copy) < $length) {
            return $copy;
        } else {
            foreach ($spaces as $space) {
                if ($space < $length) {
                    $loc = $space;
                } else {
                    return substr($copy, 0, $loc);
                }
            }
        }
    }
    

    As others have pointed out, the intent of both of these functions could probably be better expressed by using wordwrap.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?