簡體   English   中英

相當於substr和strpos的php在Python中

[英]Php equivalent of substr and strpos in 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));
}

在這里搜索但找不到解決方案。 我也試過這個:

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

要在Python中獲取子字符串(以及該問題的任何子序列),請使用切片符號 ,它類似於索引編制,但在方括號之間至少包含一個冒號:

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

您已經找出了strpos()等效項:字符串對象上的str.find()方法。 還要注意,您可以像在PHP函數中那樣為其提供附加索引:

debutpos = contentu.find(debut)
# ...
finpos = contenu.find(fin, debutpos)

當找不到子字符串時,它將返回-1。 否則,其行為類似於PHP。

因此,如果我理解正確,那么您想在contenudebut開始找到一個子字符串,並以fin contenu

因此,如果您設置

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

另外,由於您希望findebut ,因此以下步驟應該有效:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM