Python中substr和strpo的Php等价物

2024-09-28 17:02:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试将这个php-函数转换为Python:

function trouveunebrique($contenu, $debut, $fin) {
  $debutpos = strpos($contenu, $debut);
  $finpos = strpos($contenu, $fin, $debutpos);
  if ($finpos == 0) {
    $finpos = strlen($contenu);
  }
  $nbdebut = strlen($debut);
  if ($debutpos > 0) {
    $trouveunebrique = substr($contenu, ($debutpos + $nbdebut), ($finpos - $debutpos - $nbdebut));
  } 
  else {
    $trouveunebrique = "";
  }

  return (trim($trouveunebrique));
}

我搜索了here,但找不到解决方案。 我也试过了:

^{pr2}$

Tags: 函数iffunctionelsephpfinsubstrdebut
2条回答

要在Python中获取子字符串(以及与之相关的任何子序列),请使用slice notation,这与索引类似,但括号之间至少包含一个冒号:

>>> "Hello world"[4:7]
'o w'
>>> "Hello world"[:3]
'Hel'
>>> "Hello world"[8:]
'rld'

您已经找到了strpos()的等价物:string对象上的str.find()方法。另请注意,您可以像在PHP函数中那样为其提供附加索引:

^{pr2}$

如果找不到子字符串,则返回-1。否则,它的行为与PHP等效。在

如果我理解正确,你想在contenu中找到一个子串,从debut开始,到{}结束?在

所以如果你

>>> str   = "abcdefghi"
>>> debut = "bcd"
>>> fin   = "hi"

你想要:

^{pr2}$

如果是这样的话,您需要的是(string).find,它的行为类似于您的strpos

所以你的方法是这样的:

def trouveunebrique(contenu, debut, fin):
  indice_debut = contenu.find(debut)
  indice_fin = contenu.find(fin)
  return contenu[indice_debut : indice_fin + len(fin)]

或者简而言之:

def trouveunebrique(contenu, debut, fin):
 return contenu[contenu.find(debut):contenu.find(fin) + len(fin)]

另外,由于您希望您的fin位于您的debut之后,以下操作应该有效:

def trouveunebrique(contenu, debut, fin):
  indice_debut = contenu.find(debut) # find the first occurence of "debut"
  indice_fin = contenu[indice_debut:].find(fin) # find the first occurence of "fin" after "debut"
  return contenu[indice_debut : indice_debut + indice_fin + len(fin)]

相关问题 更多 >