Skip to content

Instantly share code, notes, and snippets.

@Ahmed
Created April 14, 2013 22:17
Show Gist options
  • Save Ahmed/5384476 to your computer and use it in GitHub Desktop.
Save Ahmed/5384476 to your computer and use it in GitHub Desktop.
# from: http://stackoverflow.com/questions/1228299/change-one-character-in-a-string-in-python
#
# TypeError: 'str' object does not support item assignment
# If you have a string in python and you want to replace a char by index, you will get that error.
# I searched online and a lot of people have spammed the search results with answers that are not really related.
# I found the answer on StackOverFlow, and I decided to write a small functon to implement it
# Note: it creates a new string everytime you call it.
# in [4]: replaceByIndexString(0,'@','foobar')
# Out[4]: '@oobar'
# In [5]: replaceByIndexString(1,'@','foobar')
# Out[5]: 'f@obar'
# In [6]: replaceByIndexString(2,'@','foobar')
# Out[6]: 'fo@bar'
# In [7]: replaceByIndexString(3,'@','foobar')
# Out[7]: 'foo@ar'
def replaceByIndexString(index,char,string):
tmp = list(string)
tmp[index] = char
return "".join(tmp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment