Replace first occurrence only of a string?

后端 未结 3 1831
情书的邮戳
情书的邮戳 2020-11-27 17:15

I have something like this:

text = \'This text is very very long.\'
replace_words = [\'very\',\'word\']

for word in replace_words:
    text = text.replace(\         


        
相关标签:
3条回答
  • 2020-11-27 17:51

    From http://docs.python.org/release/2.5.2/lib/string-methods.html :

    replace( old, new[, count])
    Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

    I didn't try but I believe it works

    0 讨论(0)
  • 2020-11-27 17:53
    text = text.replace("very", "not very", 1)
    

    >>> help(str.replace)
    Help on method_descriptor:
    
    replace(...)
        S.replace (old, new[, count]) -> string
    
        Return a copy of string S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
    
    0 讨论(0)
  • 2020-11-27 17:59
    text = text.replace("very", "not very", 1)
    

    The third parameter is the maximum number of occurrences that you want to replace.
    From the documentation for Python:

    string.replace(s, old, new[, maxreplace])
    Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

    0 讨论(0)
提交回复
热议问题