472,119 Members | 1,546 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,119 software developers and data experts.

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 2204
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.

Similar topics

1 post views Thread by magnolio | last post: by
2 posts views Thread by Daniel Lidström | last post: by
2 posts views Thread by Philipp | last post: by
15 posts views Thread by Sunny | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.