By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,050 Members | 1,009 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,050 IT Pros & Developers. It's quick & easy.

How to change an element of a string?

P: 5
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
Share this Question
Share on Google+
4 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
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

P: 5
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
Expert 5K+
P: 6,596
Mmm, maybe I can use the slicing to change just one element.
Yep. Like lines 5 thru 7 above do...
Nov 23 '07 #4

P: 5
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.