在Python中Php等效于substr和strpos

时间:2016-05-23 14:46:30

标签: php python python-2.7 substring strpos

我尝试将 php -function转换为 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但我无法找到解决方案。 我也试过这个:

   def trouveunebrique(contenu, debut, fin)
        debutpos = haystack.find(contenu, debut)
        finpos = haystack.find(contenu, fin)
        if (finpos == 0)
            finpos = len(contenu)
        nbdebut = len(debut)
        if (debutpos > 0):
            trouveunebrique = substr(contenu, (debutpos + nbdebut), (finpos - debutpos - nbdebut))
        else:
            trouveunebrique = ""
        return trouveunebrique.strip()

2 个答案:

答案 0 :(得分:4)

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

var mp3encoder = new lamejs.Mp3Encoder(2, 44100, 128);
// instead of `var samples = new Int16Array(44100);` I want something like `var samples = new Int16Array(blob);`
var mp3Tmp = mp3encoder.encodeBuffer(samples);

你在字符串对象上找到了strpos()等效方法:str.find()方法。另请注意,您可以像在PHP函数中一样提供其他索引:

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

找不到子字符串时返回-1。否则,它的行为就像PHP等价物。

答案 1 :(得分:1)

因此,如果我理解正确,您希望在contenu中找到一个以debut开头并以fin结束的子字符串?

所以如果你设置了

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

你想这样做:

>>> trouveunebrique(str, debut, fin)
bcdefghi

如果是这种情况,那么您所寻找的是(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)]