469,338 Members | 8,326 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,338 developers. It's quick & easy.

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
Nov 22 '07 #1
4 1968
bvdet
2,851 Expert Mod 2GB
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.
Expand|Select|Wrap|Line Numbers
  1. >>> s = '100111010100011'
  2. >>> s1 = s.replace('111', '101')
  3. >>> s1
  4. '100101010100011'
  5. >>> s2 = s1[:4]+'1'+s1[5:]
  6. >>> s2
  7. '100111010100011'
  8. >>> 
The string replace() method and slicing. The string itself is immutable, so these methods return a new string.
Nov 23 '07 #2
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.
Nov 23 '07 #3
bartonc
6,596 Expert 4TB
Mmm, maybe I can use the slicing to change just one element.
Yep. Like lines 5 thru 7 above do...
Nov 23 '07 #4
Yep. Like lines 5 thru 7 above do...
Yes, of course :D
Thanks.
Nov 23 '07 #5

Post your reply

Sign in to post your reply or Sign up for a free account.

By using this site, you agree to our Privacy Policy and Terms of Use.