The Python Oracle

Changing one character in a string

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping

--

Chapters
00:00 Question
00:22 Accepted answer (Score 720)
00:53 Answer 2 (Score 291)
01:51 Answer 3 (Score 147)
02:00 Answer 4 (Score 54)
02:36 Thank you

--

Full question
https://stackoverflow.com/questions/1228...

Accepted answer links:
[a lot]: http://effbot.org/pyfaq/why-are-python-s...

Answer 2 links:
[answer]: https://stackoverflow.com/a/1228597/2571...
[answer]: https://stackoverflow.com/a/1228332/2571...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string

#avk47



ACCEPTED ANSWER

Score 749


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.




ANSWER 2

Score 160


new = text[:1] + 'Z' + text[2:]



ANSWER 3

Score 60


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:] returns 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




ANSWER 4

Score 14


Starting with python 2.6 and python 3 you can use bytearrays which are mutable (can be changed element-wise unlike strings):

s = "abcdefg"
b_s = bytearray(s)
b_s[1] = "Z"
s = str(b_s)
print s
aZcdefg

edit: Changed str to s

edit2: As Two-Bit Alchemist mentioned in the comments, this code does not work with unicode.