Changing one character in a string
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World
--
Chapters
00:00 Changing One Character In A String
00:16 Answer 1 Score 60
00:51 Answer 2 Score 160
00:58 Accepted Answer Score 749
01:24 Answer 4 Score 14
01:44 Thank you
--
Full question
https://stackoverflow.com/questions/1228...
--
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.