As strings are immutable in Python, just create a new string which includes the value at the desired index.
Assuming you have a string s, perhaps s = "mystring"
You can quickly (and obviously) replace a portion at a desired index by placing it between "slices" of the original.
s = s[:index] + newstring + s[index + 1:]
You can find the middle by dividing your string length by 2 len(s)/2
If you're getting mystery inputs, you should take care to handle indices outside the expected range
def replacer(s, newstring, index, nofail=False):
# raise an error if index is outside of the string
if not nofail and index not in range(len(s)):
raise ValueError("index outside given string")
# if not erroring, but the index is still not in the correct range..
if index < 0: # add it to the beginning
return newstring + s
if index > len(s): # add it to the end
return s + newstring
# insert the new string between "slices" of the original
return s[:index] + newstring + s[index + 1:]
This will work as
replacer("mystring", "12", 4)
'myst12ing'
Answer from ti7 on Stack OverflowAs strings are immutable in Python, just create a new string which includes the value at the desired index.
Assuming you have a string s, perhaps s = "mystring"
You can quickly (and obviously) replace a portion at a desired index by placing it between "slices" of the original.
s = s[:index] + newstring + s[index + 1:]
You can find the middle by dividing your string length by 2 len(s)/2
If you're getting mystery inputs, you should take care to handle indices outside the expected range
def replacer(s, newstring, index, nofail=False):
# raise an error if index is outside of the string
if not nofail and index not in range(len(s)):
raise ValueError("index outside given string")
# if not erroring, but the index is still not in the correct range..
if index < 0: # add it to the beginning
return newstring + s
if index > len(s): # add it to the end
return s + newstring
# insert the new string between "slices" of the original
return s[:index] + newstring + s[index + 1:]
This will work as
replacer("mystring", "12", 4)
'myst12ing'
You can't replace a letter in a string. Convert the string to a list, replace the letter, and convert it back to a string.
>>> s = list("Hello world")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> s[int(len(s) / 2)] = '-'
>>> s
['H', 'e', 'l', 'l', 'o', '-', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello-World'
Python: String replace index - Stack Overflow
How to replace a specific index position in a list
How to replace a string that is all the same character at a specific index?
Using replace() method in python by index - Stack Overflow
Videos
you can do
s="cdabcjkewabcef"
snew="".join((s[:9],"###",s[12:]))
which should be faster than joining like snew=s[:9]+"###"+s[12:] on large strings
You can achieve this by doing:
yourString = "Hello"
yourIndexToReplace = 1 #e letter
newLetter = 'x'
yourStringNew="".join((yourString[:yourIndexToReplace],newLetter,yourString[yourIndexToReplace+1:]))
For example, you have a string that is
string1='aaaaaa'
How would I replace just the last character with 'b'?
I tried
string1=string1.replace(string1[-1],b)
But that results in 'bbbbbb' as the output. It looks like the reason is due to string1[-1] being 'a'. So it replaces every 'a' with 'b' instead of just the last one.
The problem is that .replace(old, new) returns a copy of the string in which the occurrences of old have been replaced with new.
Instead, you can swap the character at index i using:
new_str = old_str[:i] + "b" + old_str[i+1:]
Check the documentation.
You can use
example_string.replace(example_string[0], "b", 1)
though it would be much more natural to use a slice to replace just the first character, as @nbryans indicated in a comment.