【问题标题】:Find the nth occurrence of substring in a string查找字符串中第 n 次出现的子字符串
【发布时间】:2010-12-25 10:25:06
【问题描述】:

这看起来应该是微不足道的,但我是 Python 的新手,想以最 Pythonic 的方式来做。

我想找到与字符串中第 n 次出现的子字符串对应的索引。

必须有一些与我想做的事情相当的事情

mystring.find("substring", 2nd)

如何在 Python 中实现这一点?

【问题讨论】:

  • 找到第 n 次出现的字符串?我认为这意味着第 n 次出现的索引?
  • 是的,第n次出现的索引
  • 如果有重叠匹配怎么办? find_nth('aaaa', 'aa', 2) 应该返回 1 还是 2?
  • 是的!必须有一些东西可以找到字符串中第 n 次出现的子字符串,并在第 n 次出现子字符串时拆分字符串。

标签: python string substring


【解决方案1】:

对于具有基本编程知识的人的简单解决方案:

# Function to find the nth occurrence of a substring in a text
def findnth(text, substring, n):

# variable to store current index in loop
count = -1

# n count
occurance = 0

# loop through string
for letter in text:
    
    # increment count
    count += 1
    
    # if current letter in loop matches substring target
    if letter == substring:
        
        # increment occurance
        occurance += 1
        
        # if this is the nth time the substring is found
        if occurance == n:
            
            # return its index
            return count
        
# otherwise indicate there is no match
return "No match"

# example of how to call function
print(findnth('C$100$150xx', "$", 2))

【讨论】:

  • 感谢您提供答案。您能否编辑您的答案以包括对您的代码的解释?这将帮助未来的读者更好地理解正在发生的事情,尤其是那些不熟悉该语言并努力理解这些概念的社区成员。当社区已经验证了已接受的答案时,这一点尤其重要。在什么条件下你的方法可能更受欢迎?您是否在利用新功能?
【解决方案2】:

我使用了 findnth() 函数并遇到了一些问题,因此我重写了该函数的更快版本(没有列表拆分):

def findnth(haystack, needle, n):
    if not needle in haystack or haystack.count(needle) < n:
        return -1

    last_index = 0
    cumulative_last_index = 0
    for i in range(0, n):
        last_index = haystack[cumulative_last_index:].find(needle)
        cumulative_last_index += last_index
        
        # if not last element, then jump over it
        if i < n-1:
            cumulative_last_index += len(needle)

    return cumulative_last_index

【讨论】:

    【解决方案3】:

    这是一个简单而有趣的方法:

    def index_of_nth(text, substring, n) -> int:
        index = 0
        for _ in range(n):
            index = text.index(substring, index) + 1
        return index - 1
    

    【讨论】:

      【解决方案4】:

      以防万一有人想从后面找到第 n 个:

      def find_nth_reverse(haystack: str, needle: str, n: int) -> int:
          end = haystack.rfind(needle)
      
          while end >= 0 and n > 1:
              end = haystack.rfind(needle, 0, end - len(needle))
              n -= 1
      
          return end
      

      【讨论】:

        【解决方案5】:

        当提供的发生输入值高于实际发生次数时,避免失败或错误输出。例如,在字符串 'overflow' 中,如果您要检查 'o' 的第 3 次出现(它只有 2 次出现),那么下面的代码将返回一条警告或消息,指示已超过出现值。

        输入的输入出现次数超过了实际出现次数。

        def check_nth_occurrence (string, substr, n):
        
        ## Count the Occurrence of a substr
            cnt = 0
            for i in string:
                if i ==substr:
                    cnt = cnt + 1
                else:
                    pass
        
        ## Check if the Occurrence input has exceeded the actual count of Occurrence
        
            if n > cnt:
                print (f' Input Occurrence entered has exceeded the actual count of Occurrence')
                return
        
        ## Get the Index value for first Occurrence of the substr
        
           index = string.find(substr)
        
        ## Get the Index value for nth Occurrence of Index
            while index >= 0 and n > 1:
                index = string.find(substr, index+ 1)
                n -= 1
          return index
        

        【讨论】:

          【解决方案6】:

          定义:

          def get_first_N_words(mytext, mylen = 3):
              mylist = list(mytext.split())
              if len(mylist)>=mylen: return ' '.join(mylist[:mylen])
          

          使用方法:

          get_first_N_words('  One Two Three Four ' , 3)
          

          输出:

          'One Two Three'
          

          【讨论】:

            【解决方案7】:

            对于搜索第 n 次出现的字符(即长度为 1 的子字符串)的特殊情况,以下函数通过构建给定字符的所有出现位置的列表来工作:

            def find_char_nth(string, char, n):
                """Find the n'th occurence of a character within a string."""
                return [i for i, c in enumerate(string) if c == char][n-1]
            

            如果给定字符的出现次数少于n,则会给出IndexError: list index out of range

            这源自@Zv_oDD 的answer,并针对单个字符的情况进行了简化。

            【讨论】:

            • 这很漂亮。
            【解决方案8】:

            这是我在字符串a 中查找bnth 出现的解决方案:

            from functools import reduce
            
            
            def findNth(a, b, n):
                return reduce(lambda x, y: -1 if y > x + 1 else a.find(b, x + 1), range(n), -1)
            

            它是纯 Python 和迭代的。对于太大的 0 或 n,它返回 -1。它是单线的,可以直接使用。这是一个例子:

            >>> reduce(lambda x, y: -1 if y > x + 1 else 'bibarbobaobaotang'.find('b', x + 1), range(4), -1)
            7
            

            【讨论】:

              【解决方案9】:

              不使用循环和递归的解决方案。

              在编译方法中使用所需的模式并输入所需的 出现在变量 'n' 中,最后一条语句将打印 给定模式中第 n 次出现的起始索引 细绳。这里是 finditer 的结果,即迭代器正在被转换 列出并直接访问第 n 个索引。

              import re
              n=2
              sampleString="this is history"
              pattern=re.compile("is")
              matches=pattern.finditer(sampleString)
              print(list(matches)[n].span()[0])
              

              【讨论】:

                【解决方案10】:

                这将在字符串中找到第二次出现的子字符串。

                def find_2nd(string, substring):
                   return string.find(substring, string.find(substring) + 1)
                

                编辑:我没有过多考虑性能,但快速递归可以帮助找到第 n 次出现:

                def find_nth(string, substring, n):
                   if (n == 1):
                       return string.find(substring)
                   else:
                       return string.find(substring, find_nth(string, substring, n - 1) + 1)
                

                【讨论】:

                • 这可以扩展为找到第n个元素吗?
                • 这是最好的答案恕我直言,我为 n=0 的特殊情况做了一点补充
                • 为简洁起见,我不想编辑帖子。不过我同意你的观点,n=0 应该被视为一种特殊情况。
                • 这应该被调整以处理子字符串出现少于n 的情况。 (在这种情况下,返回值会周期性地循环遍历所有出现的位置)。
                【解决方案11】:
                # return -1 if nth substr (0-indexed) d.n.e, else return index
                def find_nth(s, substr, n):
                    i = 0
                    while n >= 0:
                        n -= 1
                        i = s.find(substr, i + 1)
                    return i
                

                【讨论】:

                • 需要解释
                • find_nth('aaa', 'a', 0) 返回 1 而它应该返回 0。你需要像i = s.find(substr, i) + 1 这样的东西,然后返回i - 1
                【解决方案12】:

                基于 model13 的答案,但没有 re 模块依赖项。

                def iter_find(haystack, needle):
                    return [i for i in range(0, len(haystack)) if haystack[i:].startswith(needle)]
                

                我有点希望这是一个内置的字符串方法。

                >>> iter_find("http://stackoverflow.com/questions/1883980/", '/')
                [5, 6, 24, 34, 42]
                

                【讨论】:

                  【解决方案13】:

                  这将为您提供与 yourstring 匹配的起始索引数组:

                  import re
                  indices = [s.start() for s in re.finditer(':', yourstring)]
                  

                  那么您的第 n 个条目将是:

                  n = 2
                  nth_entry = indices[n-1]
                  

                  当然,您必须小心索引范围。您可以像这样获取yourstring 的实例数:

                  num_instances = len(indices)
                  

                  【讨论】:

                    【解决方案14】:

                    这是你真正想要的答案:

                    def Find(String,ToFind,Occurence = 1):
                    index = 0 
                    count = 0
                    while index <= len(String):
                        try:
                            if String[index:index + len(ToFind)] == ToFind:
                                count += 1
                            if count == Occurence:
                                   return index
                                   break
                            index += 1
                        except IndexError:
                            return False
                            break
                    return False
                    

                    【讨论】:

                      【解决方案15】:

                      怎么样:

                      c = os.getcwd().split('\\')
                      print '\\'.join(c[0:-2])
                      

                      【讨论】:

                      【解决方案16】:

                      最简单的方法?

                      text = "This is a test from a test ok" 
                      
                      firstTest = text.find('test')
                      
                      print text.find('test', firstTest + 1)
                      

                      【讨论】:

                      • 我可以想象,与其他解决方案相比,这也相当高效。
                      【解决方案17】:

                      提供另一个“棘手”的解决方案,使用splitjoin

                      在你的例子中,我们可以使用

                      len("substring".join([s for s in ori.split("substring")[:2]]))
                      

                      【讨论】:

                        【解决方案18】:

                        我提供了一些基准测试结果,比较了迄今为止提出的最突出的方法,即@bobince 的findnth()(基于str.split())与@tgamblin 或@Mark Byers 的find_nth()(基于str.find() )。我还将与 C 扩展 (_find_nth.so) 进行比较,看看我们能走多快。这里是find_nth.py

                        def findnth(haystack, needle, n):
                            parts= haystack.split(needle, n+1)
                            if len(parts)<=n+1:
                                return -1
                            return len(haystack)-len(parts[-1])-len(needle)
                        
                        def find_nth(s, x, n=0, overlap=False):
                            l = 1 if overlap else len(x)
                            i = -l
                            for c in xrange(n + 1):
                                i = s.find(x, i + l)
                                if i < 0:
                                    break
                            return i
                        

                        当然,如果字符串很大,性能最重要,所以假设我们想在一个名为“bigfile”的 1.3 GB 文件中找到第 1000001 个换行符(“\n”)。为了节省内存,我们想处理文件的mmap.mmap 对象表示:

                        In [1]: import _find_nth, find_nth, mmap
                        
                        In [2]: f = open('bigfile', 'r')
                        
                        In [3]: mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
                        

                        findnth() 已经存在第一个问题,因为mmap.mmap 对象不支持split()。所以我们实际上必须将整个文件复制到内存中:

                        In [4]: %time s = mm[:]
                        CPU times: user 813 ms, sys: 3.25 s, total: 4.06 s
                        Wall time: 17.7 s
                        

                        哎哟!幸运的是 s 仍然适合我的 Macbook Air 的 4 GB 内存,所以让我们对 findnth() 进行基准测试:

                        In [5]: %timeit find_nth.findnth(s, '\n', 1000000)
                        1 loops, best of 3: 29.9 s per loop
                        

                        显然是糟糕的表现。让我们看看基于str.find() 的方法是如何做的:

                        In [6]: %timeit find_nth.find_nth(s, '\n', 1000000)
                        1 loops, best of 3: 774 ms per loop
                        

                        好多了!显然,findnth() 的问题在于它在split() 期间被强制复制字符串,这已经是我们在s = mm[:] 之后第二次复制大约 1.3 GB 的数据。 find_nth() 的第二个优点是:我们可以直接在 mm 上使用它,这样就需要 个文件副本:

                        In [7]: %timeit find_nth.find_nth(mm, '\n', 1000000)
                        1 loops, best of 3: 1.21 s per loop
                        

                        mms 上运行似乎存在小的性能损失,但这说明find_nth() 可以在1.2 秒内为我们提供答案,而findnth 的总时间为47 秒。

                        我没有发现基于str.find() 的方法明显比基于str.split() 的方法差的情况,所以在这一点上,我认为应该接受@tgamblin 或@Mark Byers 的答案而不是@bobince 的答案。

                        在我的测试中,上面find_nth() 的版本是我能想到的最快的纯Python 解决方案(与@Mark Byers 的版本非常相似)。让我们看看使用 C 扩展模块可以做得更好。这里是_find_nthmodule.c

                        #include <Python.h>
                        #include <string.h>
                        
                        off_t _find_nth(const char *buf, size_t l, char c, int n) {
                            off_t i;
                            for (i = 0; i < l; ++i) {
                                if (buf[i] == c && n-- == 0) {
                                    return i;
                                }
                            }
                            return -1;
                        }
                        
                        off_t _find_nth2(const char *buf, size_t l, char c, int n) {
                            const char *b = buf - 1;
                            do {
                                b = memchr(b + 1, c, l);
                                if (!b) return -1;
                            } while (n--);
                            return b - buf;
                        }
                        
                        /* mmap_object is private in mmapmodule.c - replicate beginning here */
                        typedef struct {
                            PyObject_HEAD
                            char *data;
                            size_t size;
                        } mmap_object;
                        
                        typedef struct {
                            const char *s;
                            size_t l;
                            char c;
                            int n;
                        } params;
                        
                        int parse_args(PyObject *args, params *P) {
                            PyObject *obj;
                            const char *x;
                        
                            if (!PyArg_ParseTuple(args, "Osi", &obj, &x, &P->n)) {
                                return 1;
                            }
                            PyTypeObject *type = Py_TYPE(obj);
                        
                            if (type == &PyString_Type) {
                                P->s = PyString_AS_STRING(obj);
                                P->l = PyString_GET_SIZE(obj);
                            } else if (!strcmp(type->tp_name, "mmap.mmap")) {
                                mmap_object *m_obj = (mmap_object*) obj;
                                P->s = m_obj->data;
                                P->l = m_obj->size;
                            } else {
                                PyErr_SetString(PyExc_TypeError, "Cannot obtain char * from argument 0");
                                return 1;
                            }
                            P->c = x[0];
                            return 0;
                        }
                        
                        static PyObject* py_find_nth(PyObject *self, PyObject *args) {
                            params P;
                            if (!parse_args(args, &P)) {
                                return Py_BuildValue("i", _find_nth(P.s, P.l, P.c, P.n));
                            } else {
                                return NULL;    
                            }
                        }
                        
                        static PyObject* py_find_nth2(PyObject *self, PyObject *args) {
                            params P;
                            if (!parse_args(args, &P)) {
                                return Py_BuildValue("i", _find_nth2(P.s, P.l, P.c, P.n));
                            } else {
                                return NULL;    
                            }
                        }
                        
                        static PyMethodDef methods[] = {
                            {"find_nth", py_find_nth, METH_VARARGS, ""},
                            {"find_nth2", py_find_nth2, METH_VARARGS, ""},
                            {0}
                        };
                        
                        PyMODINIT_FUNC init_find_nth(void) {
                            Py_InitModule("_find_nth", methods);
                        }
                        

                        这是setup.py 文件:

                        from distutils.core import setup, Extension
                        module = Extension('_find_nth', sources=['_find_nthmodule.c'])
                        setup(ext_modules=[module])
                        

                        使用python setup.py install 照常安装。 C 代码在这里发挥了优势,因为它仅限于查找单个字符,但让我们看看这有多快:

                        In [8]: %timeit _find_nth.find_nth(mm, '\n', 1000000)
                        1 loops, best of 3: 218 ms per loop
                        
                        In [9]: %timeit _find_nth.find_nth(s, '\n', 1000000)
                        1 loops, best of 3: 216 ms per loop
                        
                        In [10]: %timeit _find_nth.find_nth2(mm, '\n', 1000000)
                        1 loops, best of 3: 307 ms per loop
                        
                        In [11]: %timeit _find_nth.find_nth2(s, '\n', 1000000)
                        1 loops, best of 3: 304 ms per loop
                        

                        显然还是要快很多。有趣的是,内存中的情况和映射的情况在 C 级别上没有区别。同样有趣的是,基于string.hmemchr() 库函数的_find_nth2() 输给了_find_nth() 中的直接实现:memchr() 中的额外“优化”显然适得其反。 ..

                        总之,findnth()(基于str.split())中的实现确实是个坏主意,因为(a)由于需要复制,它对较大的字符串执行得非常糟糕,以及(b) 它根本不适用于mmap.mmap 对象。在任何情况下都应该首选find_nth()(基于str.find())中的实现(因此是这个问题的公认答案)。

                        仍有相当大的改进空间,因为 C 扩展的运行速度几乎是纯 Python 代码的 4 倍,这表明可能需要专门的 Python 库函数。

                        【讨论】:

                          【解决方案19】:

                          更换一个衬里很棒,但只能工作,因为 XX 和 bar 具有相同的 lentgh

                          一个好的通用定义是:

                          def findN(s,sub,N,replaceString="XXX"):
                              return s.replace(sub,replaceString,N-1).find(sub) - (len(replaceString)-len(sub))*(N-1)
                          

                          【讨论】:

                            【解决方案20】:

                            这里是直接迭代解决方案的更 Pythonic 版本:

                            def find_nth(haystack, needle, n):
                                start = haystack.find(needle)
                                while start >= 0 and n > 1:
                                    start = haystack.find(needle, start+len(needle))
                                    n -= 1
                                return start
                            

                            例子:

                            >>> find_nth("foofoofoofoo", "foofoo", 2)
                            6
                            

                            如果你想找到needle的第n个重叠,你可以增加1而不是len(needle),像这样:

                            def find_nth_overlapping(haystack, needle, n):
                                start = haystack.find(needle)
                                while start >= 0 and n > 1:
                                    start = haystack.find(needle, start+1)
                                    n -= 1
                                return start
                            

                            例子:

                            >>> find_nth_overlapping("foofoofoofoo", "foofoo", 2)
                            3
                            

                            这比Mark的版本更容易阅读,而且不需要拆分版本的额外内存或导入正则表达式模块。它还遵守Zen of python 中的一些规则,与各种re 方法不同:

                            1. 简单胜于复杂。
                            2. 平面优于嵌套。
                            3. 可读性很重要。

                            【讨论】:

                            • 这可以在字符串中完成吗?像 find_nth(df.mystring.str, ('x'), 2) 来查找'x'的第二个实例的位置?
                            • find_nth 的建议文档字符串:"""Finds index of the *n*'th occurrence of *needle* within *haystack*. Returns -1 when the *n*'th occurrence is not found."""
                            • find_nth 可以扩展以支持 haystack 中的起始位置,方法是添加第四个 arg 'start_position=0',然后将第一行修改为 start = haystack.find(needle, start_position)
                            【解决方案21】:

                            这是另一个re + itertools 版本,在搜索strRegexpObject 时应该可以使用。我会坦率地承认,这可能是过度设计的,但出于某种原因,它让我很开心。

                            import itertools
                            import re
                            
                            def find_nth(haystack, needle, n = 1):
                                """
                                Find the starting index of the nth occurrence of ``needle`` in \
                                ``haystack``.
                            
                                If ``needle`` is a ``str``, this will perform an exact substring
                                match; if it is a ``RegexpObject``, this will perform a regex
                                search.
                            
                                If ``needle`` doesn't appear in ``haystack``, return ``-1``. If
                                ``needle`` doesn't appear in ``haystack`` ``n`` times,
                                return ``-1``.
                            
                                Arguments
                                ---------
                                * ``needle`` the substring (or a ``RegexpObject``) to find
                                * ``haystack`` is a ``str``
                                * an ``int`` indicating which occurrence to find; defaults to ``1``
                            
                                >>> find_nth("foo", "o", 1)
                                1
                                >>> find_nth("foo", "o", 2)
                                2
                                >>> find_nth("foo", "o", 3)
                                -1
                                >>> find_nth("foo", "b")
                                -1
                                >>> import re
                                >>> either_o = re.compile("[oO]")
                                >>> find_nth("foo", either_o, 1)
                                1
                                >>> find_nth("FOO", either_o, 1)
                                1
                                """
                                if (hasattr(needle, 'finditer')):
                                    matches = needle.finditer(haystack)
                                else:
                                    matches = re.finditer(re.escape(needle), haystack)
                                start_here = itertools.dropwhile(lambda x: x[0] < n, enumerate(matches, 1))
                                try:
                                    return next(start_here)[1].start()
                                except StopIteration:
                                    return -1
                            

                            【讨论】:

                              【解决方案22】:
                              >>> s="abcdefabcdefababcdef"
                              >>> j=0
                              >>> for n,i in enumerate(s):
                              ...   if s[n:n+2] =="ab":
                              ...     print n,i
                              ...     j=j+1
                              ...     if j==2: print "2nd occurence at index position: ",n
                              ...
                              0 a
                              6 a
                              2nd occurence at index position:  6
                              12 a
                              14 a
                              

                              【讨论】:

                                【解决方案23】:

                                这是使用 re.finditer 的另一种方法。
                                不同的是,这只是在必要时查看干草堆

                                from re import finditer
                                from itertools import dropwhile
                                needle='an'
                                haystack='bananabanana'
                                n=2
                                next(dropwhile(lambda x: x[0]<n, enumerate(re.finditer(needle,haystack))))[1].start() 
                                

                                【讨论】:

                                  【解决方案24】:

                                  我可能会做这样的事情,使用带有索引参数的 find 函数:

                                  def find_nth(s, x, n):
                                      i = -1
                                      for _ in range(n):
                                          i = s.find(x, i + len(x))
                                          if i == -1:
                                              break
                                      return i
                                  
                                  print find_nth('bananabanana', 'an', 3)
                                  

                                  我猜这不是特别 Pythonic,但它很简单。您可以使用递归来代替:

                                  def find_nth(s, x, n, i = 0):
                                      i = s.find(x, i)
                                      if n == 1 or i == -1:
                                          return i 
                                      else:
                                          return find_nth(s, x, n - 1, i + len(x))
                                  
                                  print find_nth('bananabanana', 'an', 3)
                                  

                                  这是一种解决问题的实用方法,但我不知道这是否使它更 Pythonic。

                                  【讨论】:

                                  • for _ in xrange(n):可以代替while n: ... n-=1
                                  • @J.F. Sebastian:是的,我想这更像是 Pythonic。我会更新的。
                                  • 顺便说一句:Python 3 中不再需要 xrange:diveintopython3.org/…
                                  • return find_nth(s, x, n - 1, i + 1) 应该是 return find_nth(s, x, n - 1, i + len(x))。没什么大不了的,但节省了一些计算时间。
                                  • @dlo:实际上在某些情况下会给出不同的结果:find_nth('aaaa','aa',2)。我的给 1,你的给 2。我猜你的实际上是海报想要的。我会更新我的代码。感谢您的评论。
                                  【解决方案25】:

                                  了解正则表达式并不总是最好的解决方案,我可能会在这里使用一个:

                                  >>> import re
                                  >>> s = "ababdfegtduab"
                                  >>> [m.start() for m in re.finditer(r"ab",s)]
                                  [0, 2, 11]
                                  >>> [m.start() for m in re.finditer(r"ab",s)][2] #index 2 is third occurrence 
                                  11
                                  

                                  【讨论】:

                                  • 这里的风险当然是要搜索的字符串将包含特殊字符,这些字符会导致正则表达式执行您不想要的操作。使用 re.escape 应该可以解决这个问题。
                                  • 这很聪明,但它真的是 Pythonic 吗?仅仅找到第 n 次出现的子字符串似乎有点矫枉过正,而且它并不容易阅读。另外,就像你说的,你必须为此导入所有的 re
                                  • 当你使用方括号时,你告诉 Python 创建整个列表。圆括号只会遍历第一个元素,这样更有效:(m.start() for m in re.finditer(r"ab",s))[2]
                                  • @emu 不,您发布的内容无效;您不能获取生成器的索引。
                                  • @MarkAmery 对不起!我很惊讶为什么我发布了那个代码。不过,使用itertools.islice 函数可以实现类似且丑陋的解决方案:next(islice(re.finditer(r"ab",s), 2, 2+1)).start()
                                  【解决方案26】:

                                  我认为,Mark 的迭代方法将是通常的方法。

                                  这里有一个字符串分割的替代方案,它通常对查找相关的过程很有用:

                                  def findnth(haystack, needle, n):
                                      parts= haystack.split(needle, n+1)
                                      if len(parts)<=n+1:
                                          return -1
                                      return len(haystack)-len(parts[-1])-len(needle)
                                  

                                  这里有一个快速(而且有点脏,因为你必须选择一些无法匹配针的箔条)单线:

                                  'foo bar bar bar'.replace('bar', 'XXX', 1).find('bar')
                                  

                                  【讨论】:

                                  • 当你感兴趣的匹配接近开始时,第一个建议对于大字符串来说效率很低。它总是查看整个字符串。这很聪明,但我不会向刚接触 Python 并且只想学习一种好方法的人推荐它。
                                  • 谢谢,我喜欢你的一个班轮。我不认为它是世界上最易读的东西,但它并不比下面的大多数其他东西差多少
                                  • +1 表示单线,这现在应该对我有帮助。我一直在考虑做与.rfind('XXX') 等效的操作,但如果'XXX' 无论如何都出现在输入的后面,那将分崩离析。
                                  • 这个函数假设 n = 0, 1, 2, 3, ... 如果你假设 n = 1, 2, 3, 4, ...
                                  猜你喜欢
                                  • 1970-01-01
                                  • 2018-08-24
                                  • 2011-02-04
                                  • 2018-03-22
                                  • 2021-02-10
                                  • 2016-05-07
                                  • 2022-01-18
                                  • 1970-01-01
                                  相关资源
                                  最近更新 更多