-2

In this code here

x = '123'

How can I addition let's say 5 to the second index. So x would be '173'.

aaa
  • 93
  • 1
  • 7

3 Answers3

2
x = '123'
n = 5

result = x[:1] + str(int(x[1]) + n) + x[2:]
print(result)

Prints:

173

For n=9:

1113
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

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].

cs1349459
  • 911
  • 9
  • 27
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

wjandrea
  • 28,235
  • 9
  • 60
  • 81