Python, 将字符串附加为值

huangapple go评论59阅读模式
英文:

Python, append string as value

问题

你好,以下是翻译好的部分:

我是新手学习Python,有没有一种方法可以在Python中将字符串附加为值。

例如:

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

现在很容易。但在我的特殊情况下,我必须做类似这样的事情。

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

我的计划是当我打印(a)时,它应该类似于['123', '234', '345']。实际上,它的输出是['b0', 'b1', 'b2']。

那么,我应该如何修复这个问题。

英文:

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.

答案1

得分: 1

使用字典不要在不需要的地方使用`str`。

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

a = []
for i in range(3):
a.append(var[f"b{i}"])


<details>
<summary>英文:</summary>

Use a dictionary.  Don&#39;t use `str` where it isn&#39;t required.

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

a = []
for i in range(3):
a.append(var[f"b{i}"])


</details>



# 答案2
**得分**: 0

```python
b_dict = {
    'b0': '123',
    'b1': '234',
    'b2': '345'
}

a = []
for i in range(3):
    z = 'b' + str(i)
    a.append(b_dict.get(z))
英文:
b_dict = {
    &#39;b0&#39;: &#39;123&#39;,
    &#39;b1&#39;: &#39;234&#39;,
    &#39;b2&#39;: &#39;345&#39;
}

a = []
for i in range(3):
    z = &#39;b&#39; + 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.

答案3

得分: -1

a = []
for i in range(0, 3):
    z = '%i%i%i' % (i, i+1, i+2)
    a.append(z)
英文:
a=[]
for i in range (0,3):
     z=&#39;%i%i%i&#39; %(i,i+1,i+2)
     a.append(z)

huangapple
  • 本文由 发表于 2023年2月27日 10:58:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75576425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定