簡體   English   中英

python將數字添加到字符串

[英]python adding number to string

嘗試將count int添加到字符串的末尾(網站URL)

碼:

  count = 0
  while count < 20:
    Url = "http://www.ihiphopmusic.com/music/page/" 
    Url = (Url) + (count)
    #Url = Url.append(count)
    print Url

我想要:

http://www.ihiphopmusic.com/music/page/2
http://www.ihiphopmusic.com/music/page/3
http://www.ihiphopmusic.com/music/page/4
http://www.ihiphopmusic.com/music/page/5

結果:

Traceback (most recent call last):
  File "grub.py", line 7, in <module>
    Url = Url + (count)
TypeError: cannot concatenate 'str' and 'int' objects

問題正是回溯所說的。 Python不知道如何處理"hello" + 12345

您必須先將整數count轉換為字符串。

此外,您永遠不會遞增count變量,因此您的while循環將永遠繼續。

嘗試這樣的事情:

count = 0
url = "http://example.com/"
while count < 20:
    print(url + str(count))
    count += 1

甚至更好:

url = "http://example.com/"
for count in range(1, 21):
    print(url + str(count))

正如Just_another_dunce指出的那樣,在Python 2.x中,您也可以這樣做

print url + str(count)

嘗試

 Url = (Url) + str(count)

代替。 問題是你試圖連接一個字符串和一個數字 ,而不是兩個字符串。 str()會為你解決這個問題。

str()將提供適合串聯的字符串count版本,而不實際將count轉換為int中的字符串。 看這個例子:

>>> n = 55

>>> str(n)
>>> '55'

>>> n
>>> 55

最后,格式化字符串被認為更有效,而不是連接它。 也就是說,

 Url = '%s%d' % (Url, count)

要么

 Url = '{}{}'.format(Url, count)

此外,您有一個無限循環,因為count的值永遠不會在循環內更改。 要修復此添加

count += 1

在循環的底部。

嘗試將計數轉換為字符串,如下所示

Url = "http://www.ihiphopmusic.com/music/page/" + str(count)

或使用格式

Url = "http://www.ihiphopmusic.com/music/page/%s" % count

或者甚至是

Url = "http://www.ihiphopmusic.com/music/page/{count}".format(count=count) 
Url = "http://www.ihiphopmusic.com/music/page/%d" % (count,)

用這個:

url = "http://www.ihiphopmusic.com/music/page/" while count < 20: '''You can redefine the variable Also, you have to convert count to a string as url is also a string''' url = url + str(count) print url

您必須將int更改為字符串。

Url = (Url) + str(count)

您需要將整數轉換為字符串

count = 0
while count < 20:
    Url = "http://www.ihiphopmusic.com/music/page/"
    Url = (Url) + str(count)     
    #Url = Url.append(count)     
    print Url 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM