Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing one character of a string in python

Tags:

python

In python, are strings mutable? The line someString[3] = "a" throws the error

TypeError: 'str' object does not support item assignment

I can see why (as I could have written someString[3] = "test" and that would obviously be illegal) but is there a method to do this in python?

like image 655
Chris Avatar asked Jan 29 '10 21:01

Chris


People also ask

How do I replace only one character in a string?

Like StringBuilder, the StringBuffer class has a predefined method for this purpose – setCharAt(). Replace the character at the specific index by calling this method and passing the character and the index as the parameter.

How do you replace only one occurrence of a string in Python?

replace (old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

How do I replace text in a string?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.


1 Answers

Python strings are immutable, which means that they do not support item or slice assignment. You'll have to build a new string using i.e. someString[:3] + 'a' + someString[4:] or some other suitable approach.

like image 186
Håvard S Avatar answered Oct 08 '22 15:10

Håvard S