Python: replace terms in a string except for the last

后端 未结 3 1831
北海茫月
北海茫月 2020-12-20 14:17

How does one go about replacing terms in a string - except for the last, which needs to be replaced to something different?

An example:

    letters =         


        
相关标签:
3条回答
  • 2020-12-20 14:25
    letters = 'a;b;c;d'
    lettersOut = ' & '.join(letters.replace(';', ', ').rsplit(', ', 1))
    print(lettersOut)
    
    0 讨论(0)
  • 2020-12-20 14:32

    In str.replace you can also pass an optional 3rd argument(count) which is used to handle the number of replacements being done.

    In [20]: strs = 'a;b;c;d'
    
    In [21]: count = strs.count(";") - 1
    
    In [22]: strs = strs.replace(';', ', ', count).replace(';', ' & ')
    
    In [24]: strs
    Out[24]: 'a, b, c & d'
    

    Help on str.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-12-20 14:51

    Another way of doing it in one line without knowing the number of occurrences:

    letters = 'a;b;c;d'
    letters[::-1].replace(';', ' & ', 1)[::-1].replace(';', ', ')
    
    0 讨论(0)
提交回复
热议问题