1

I have a list called x below and I want to replace the ">" (in x[0][0]) with the integer 1.

x = [">000#","#0#00","00#0#"]

I tried x[0][0] = 1 but it gives me an error.

Also, can I make x[0][2] to become an integer such that x[0][2] += 1 becomes this: x = ["1010#","#0#00","00#0#"]

Nick
  • 138,499
  • 22
  • 57
  • 95

2 Answers2

1

Python strings are immutable; you cannot change their contents. Instead, you need to make a new string out of the old one and assign that to x[0]:

x = [">000#","#0#00","00#0#"]
# change the first character to a '1'
x[0] = '1' + x[0][1:]
# add 1 to the third character
x[0] = x[0][:2] + str(int(x[0][2]) + 1) + x[0][3:]
print(x)

Output:

['1010#', '#0#00', '00#0#']
Nick
  • 138,499
  • 22
  • 57
  • 95
  • SomeRandomPersonD Please see my edit, it also addresses the second part of your question – Nick Mar 12 '20 at 13:28
1

You can try

 x[0]=x[0].replace(">","1")

Strings are immutable so cant be changed like list.

Or you can convert to list.

x[0]=list(x[0])
x[0][0]="1"
x[0][2]=str(int(x[0][2])+1)
x[0]="".join(x[0])
vks
  • 67,027
  • 10
  • 91
  • 124