2017-04-24 76 views
1

所以我得到這個如何將一個整數添加到字符串?

 itemIds1 = ('2394328') 
     itemIds2 = ('6546345') 
     count2 = 1 
     itemIdsCount = ('itemIds' + count2) 
     while (count2 < 2): 
       #Do stuff 
       count2 = count2 + 1 

我不知道如果我解釋說這是正確的。但是在第4行中,我想讓字符串等於itemIds1,然後一旦它看起來使它等於itemsIds2。

如果你不知道我顯然是Python的新手,所以如果你能解釋清楚該做什麼,那將是非常棒的。

+0

'itemIdsCount = 「itemIds%d」 %count2'我想會做你想要什麼,不是嗎? – Fallenreaper

回答

0

下面創建你需要的字符串:

itemIdsCount = "itemIds%d" % count2 

所以你可以看一下蟒蛇的字符串,看你如何使用%S,%d和其他注入後會發生什麼。

作爲additionalNote,如果需要追加多個項目,你就需要說的是這樣的:

itemIdsCount = "Id:%d Name:%s" % (15, "Misha") 
3

以下是可能的選項:

  1. 使用%s

    itemIdsCount ='itemIds%s'+ count

  2. 角色整數字符串第一

    itemIdsCount = 'itemIds' + STR(計數)

  3. 使用.format()方法

    itemIdsCount = 'itemIds {}'。格式(計數)

  4. 如果你有蟒蛇3.6,你可以使用F-字符串(文本字符串插值)

    數= 1

    itemIdsCount = {f'itemIds計數}」

+0

不要忘記Python中的f-strings> = 3.6! 'f'itemIds {count2}'' – Tutleman

+0

@Tutleman非常感謝你。我更新了我的答案 –

-1

如果你需要等於字符串和整數,也許你應該使用str(x)或int(x)。在這種情況下itemIdsCount =( 'itemIds' + STR(COUNT2))

1

您可以使用format,即:

count2 = 1 
    itemIdsCount = ('itemIds{}'.format(count2)) 
    while (count2 < 2): 
      #Do stuff 
      count2 += 1 # it's simpler like this 
+0

工作謝謝。 –