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条)

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗