In this code here
x = '123'
How can I addition let's say 5 to the second index. So x would be '173'
.
In this code here
x = '123'
How can I addition let's say 5 to the second index. So x would be '173'
.
x = '123'
n = 5
result = x[:1] + str(int(x[1]) + n) + x[2:]
print(result)
Prints:
173
For n=9
:
1113
Split it into a list, try to turn them into ints or floats, and do your math.
x = "123"
x = list(x)
for i in range(0, len(x)):
try:
x[i] = int(x[i])
except:
x[i] = x[i]
x[1] += 5
print(x)
It returns [1.0, 7.0, 3.0].
Split the string into a list, modify the element at the desired index, then join the list back into a string.
x = '123'
i = 1
n = 5
y = list(x)
y[i] = str(int(y[i]) + n)
print(''.join(y)) # -> 173
Based on scvalex's answer on Changing one character in a string in Python