find a given string and added a single character at the end of that string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jmagill
    New Member
    • Sep 2013
    • 1

    find a given string and added a single character at the end of that string

    Hi
    I want to find single occurrence of "season ?" where ? is any single digit 1-9 and replace it with season 0? cannot simply replace season with season 0 as there are season 0? which are not to be changed.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Here's a re solution:
    Code:
    import re
    
    s = 'I want to find single occurrence of "season 08" where ? is any single digit 1-9 and season 91 season 4 season 5 abcdef'
    
    patt = re.compile(r'(season [1-9](?![0-9]))')
    
    m = patt.search(s)
    if m:
        s = re.sub(patt, 'season 0' + m.group(1)[-1], s, 1)
    
    print s
    The output:
    Code:
    >>> I want to find single occurrence of "season 08" where ? is any single digit 1-9 and season 91 season 04 season 5 abcdef

    Comment

    Working...