tags:

views:

1473

answers:

4

What is the easiest way in python to replace a character in a string like:

text = "abcdefg";
text[1] = "Z";
           ^
A: 

Python strings are immutable, you change them by making a copy.
The easiest way to do what you want is probably.

text = "Z" + text[1:]

The text[1:] return the string in text from position 1 to the end, positions count from 0 so '1' is the second character.

edit: You can use the same string slicing technique for any part of the string

text = text[:1] + "Z" + text[2:]

Or if the letter only appears once you can use the search and replace technique suggested below

Martin Beckett
I ment the 2nd character, IE. the character at place number 1 (as apposed to the 1st character, number 0)
kkaploon
text[0] + "Z" + text[2:]
wbg
+5  A: 
new = text[:1] + 'Z' + text[2:]
THC4k
The first is fine, but the second replaces the first occurrence of b with Z, which is not necessarily at index 1 like in the OP's example.
Kiv
+10  A: 

Don't modify strings.

Work with them as lists; turn them into strings only when needed.

>>> s = list("Hello zorld")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[6] = 'W'
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello World'

Python strings are immutable (i.e. they can't be modified). There are a lot of reasons for this. Use lists until you have no choice, only then turn them into strings.

scvalex
+1  A: 

Like other people have said, generally Python strings are supposed to be immutable.

However, if you are using CPython, the implementation at python.org, it is possible to use ctypes to modify the string structure in memory.

Here is an example where I use the technique to clear a string.

http://stackoverflow.com/questions/982682/mark-data-as-sensitive-in-python/983525#983525

I mention this for the sake of completeness, and this should be your last resort as it is hackish.

Unknown