Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to use Mathematica to make some work on binary data, and I'm missing something.

Consider the string "111". I want to flip the last bit to become "110". My guess would be to use StringReplacePart, but I'm struggling to achieve this:

StringReplacePart["111", "0", 3]  (* returns "0" *)

What is the function for replacing a single character at a given position?

share|improve this question
You need {3, 3} as the last argument... that's the only documented form. It looks like using just 3 is equivalent to {1, 3}, but is undocumented. – R. M. Jan 8 '14 at 16:04
-.-' I needed it in a middle position and because, strangely enough, StringReplacePart["111", "0", -1] works, I assumed the notation was consistent. Thanks @rm-rf, feel free to add an answer. – J. C. Leitão Jan 8 '14 at 16:08
The last part of my answer explains why -1 worked differently. It seems like for negative indices, it is equivalent to {n, -1}. – R. M. Jan 8 '14 at 16:23
up vote 1 down vote accepted

The documented form of StringReplacePart is

StringReplacePart["string", "snew", {m, n}]

where the replacement is done from positions m through n. In your case, you would need {3, 3}:

StringReplacePart["111", "0", {3, 3}]
(* "110" *)

You can also use -1 as the index for the last element (useful when the string length is unknown).

Using only an integer n as the last argument doesn't seem to be documented, but from a quick test, it appears to be the same as {1, n} for positive n and {n, -1} for negative n.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.