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 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)