I want to be able to replace a part of a string but i dont need it to be a specific character to be replaced, instead i want to replace the last part of a string. like s[-1]. so how do I do this?
5 Answers
Strings are immutable, so you cannot "replace" a character in-place. You will need to create a new string (by slicing your old one and concatenating with whatever) and then assigning that to something, perhaps over your old reference.
foo = 'foo'
foo[:-1] + 'x'
Out[31]: 'fox'
foo
Out[32]: 'foo'
foo = foo[:-1] + 'x'
foo
Out[34]: 'fox'

- 25,533
- 4
- 48
- 73
I think the simplest solution would be to use Explain Python's slice notation and slice the string up to the position you want. Then, you can add on a new ending.
See a demonstration below:
>>> mystr = "abcde"
>>> mystr[:-1]+"x"
'abcdx'
>>>

- 1
- 1
Well, if it's just the last part one could use something like:
new_string = old[:x] + "new bit"
which would return a copy of the first part, and concatenate it with then new part. However, you might avoid copying, if the new bit is of the same length as the part you are replacing.

- 379
- 2
- 5
this is a way to do this:
>>> a = "my damn strin"
>>> b = a[:-1]
>>> b = b + 'k'
>>> b
'my damn strik'
>>>

- 6,482
- 6
- 36
- 55
Doing string slicing and concatenation is probably the best way, but here's an alternative way that may be faster in case you care about that. It uses an array of unsigned char, which is essentially a mutable string.
#!/usr/local/cpython-3.3/bin/python
import array as array_mod
string = b'sequence of characterx'
array = array_mod.array('B', string)
print(array)
array[-1] = ord(b's')
print(array)
HTH

- 6,954
- 1
- 26
- 27