0

I am new to python, is there a way to append string in python as value.

For example:

b0 = str("123")
b1 = str("234")
b2 = str("345")

Easy for now. But in my special case, I have to doing somethings like this.

a = []
for i in range (0,3):
    z = str("b") + str("i")
    a.append(z)

My plan is when I print(a), it should somethings like ['123', '234', '345']. In fact, it doing like this['b0', 'b1', 'b2'].

So, how can I fix this.

FH Lm
  • 11
  • 2
  • Nope, Python doesn't work that way. What you need is a dictionary. Create `var['b0'] = "123"`, `var['b1'] = "234"`, `var['b2'] = "345"`. That's the right way. BTW, you do not need `str("123")`; that's already a string. – Tim Roberts Feb 27 '23 at 03:01
  • @FHLm Well, your example actually produces `['bi', 'bi', 'bi']` – qrsngky Feb 27 '23 at 03:03

3 Answers3

1

Use a dictionary. Don't use str where it isn't required.

var['b0'] = "123"
var['b1'] = "234"
var['b2'] = "345"

a = []
for i in range(3):
    a.append(var[f"b{i}"])
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0
b_dict = {
    'b0': '123',
    'b1': '234',
    'b2': '345'
}

a = []
for i in range(3):
    z = 'b' + str(i)
    a.append(b_dict.get(z))

I'm also a beginner. She doesn't know why you're doing this, but that's one way I'm thinking about it, I'm going to use the dict.

Yulisa
  • 1
  • 1
-1
a=[]
for i in range (0,3):
     z='%i%i%i' %(i,i+1,i+2)
     a.append(z)