Regarding replace

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sashi2keng
    New Member
    • Feb 2010
    • 4

    Regarding replace

    Hi,

    I have a string like this:
    str = "ppp= ['wwww', 'ttttt']\n"

    Now in this, I want to remove 'ttttt'. After removing it should be like this:
    "ppp= ['wwww']\n"

    How can I acheive this? I am not able to achieve this using string replace.
    Appreciate the help.

    Thanks,
    Sashi.
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Are there always 2 items in the "list"?

    It might be easiest to get rid of the /n and then use an eval to create the list. Then delete it from the list. Then recreate the string from the list.

    Comment

    • Motoma
      Recognized Expert Specialist
      • Jan 2007
      • 3236

      #3
      Following on the heals of Glenton's questions: what is the determining factor for removing 'ttttt'? Are you looking to remove the nth element of the string or an exact substring?

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Sometimes re comes in handy. The following will match and replace the last part of the string.
        Code:
        >>> import re
        >>> s1 = "ppp= ['wwww', 'ttttt']\n"
        >>> patt = re.compile(r", *'[a-zA-Z0-9]+?'\]\n")
        >>> patt.sub("]\n", s1)
        "ppp= ['wwww']\n"
        >>> s2 = "zzz =  ['rrrr', 'tttt', 'x1Tfio']\n"
        >>> patt.sub("]\n", s2)
        "zzz =  ['rrrr', 'tttt']\n"
        >>>

        Comment

        Working...