search and replace with variable value

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nischalinn
    New Member
    • Mar 2014
    • 16

    #1

    search and replace with variable value

    I've to search for a pattern and replace with input variable.
    Suppose the strings are:

    tempSearch : = '111-452-05'
    tempSearch:= '111-452-10'
    tempSearch:='11 1-459-15'
    tempSearch: ='111-452-20'
    tempSearch:='11 1-452-25'

    search for the whole pattern starting from the "temp" to the end "'". I've to replace the value that is occuring after the first appearance of "-" with a user input value.

    How can I do it?

    Thank You!
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Using str methods only:
    Code:
    >>> s = "tempSearch : = '111-452-05'"
    >>> userStr = "XYZ"
    >>> s[:s.index("-")+1]+userStr
    "tempSearch : = '111-XYZ"
    >>>
    Using re and str methods:
    Code:
    >>> import re
    >>> s = "tempSearch : = '111-452-05'"
    >>> userStr = "XYZ"
    >>> patt = re.compile(r"-(.+)")
    >>> m = patt.search(s)
    >>> s.replace(m.group(1), userStr)
    "tempSearch : = '111-XYZ"
    >>>

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      Take a look at "Searching Text" and "Replacing Text" at http://www.freenetpages.co.uk/hp/alan.gauld/tuttext.htm You can also split on the "-" if that is easier to understand.
      Code:
      testing="tempSearch : = '111-452-05'"
      replaced = "new part"
      parts = testing.split("-")
      print "parts =", parts
      parts[1]=replaced
      print "-".join(parts)

      Comment

      • nischalinn
        New Member
        • Mar 2014
        • 16

        #4
        Thanks for the reply guys!!!

        Comment

        Working...