How to change an element of a string?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ilSignorCarlo
    New Member
    • Nov 2007
    • 5

    How to change an element of a string?

    Hi,

    in an application I'm developing I need to change some elements in a string. It contains just 1 and 0, and I need to change, sometimes, a particular 1 to 0 or viceversa.

    Is there any simple method to do this?

    Thanks,
    Carlo
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by ilSignorCarlo
    Hi,

    in an application I'm developing I need to change some elements in a string. It contains just 1 and 0, and I need to change, sometimes, a particular 1 to 0 or viceversa.

    Is there any simple method to do this?

    Thanks,
    Carlo
    There are a couple of ways you can approach this.[code=Python]>>> s = '10011101010001 1'
    >>> s1 = s.replace('111' , '101')
    >>> s1
    '10010101010001 1'
    >>> s2 = s1[:4]+'1'+s1[5:]
    >>> s2
    '10011101010001 1'
    >>> [/code]The string replace() method and slicing. The string itself is immutable, so these methods return a new string.

    Comment

    • ilSignorCarlo
      New Member
      • Nov 2007
      • 5

      #3
      Originally posted by bvdet
      The string replace() method and slicing. The string itself is immutable, so these methods return a new string.
      Mmm, maybe I can use the slicing to change just one element.

      Comment

      • bartonc
        Recognized Expert Expert
        • Sep 2006
        • 6478

        #4
        Originally posted by ilSignorCarlo
        Mmm, maybe I can use the slicing to change just one element.
        Yep. Like lines 5 thru 7 above do...

        Comment

        • ilSignorCarlo
          New Member
          • Nov 2007
          • 5

          #5
          Originally posted by bartonc
          Yep. Like lines 5 thru 7 above do...
          Yes, of course :D
          Thanks.

          Comment

          Working...