python将数字添加到字符串

标签 python

<分区>

尝试在字符串(网站 url) 的末尾添加一个 int 计数:

代码:

  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)

关于python将数字添加到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11999228/

相关文章:

python - 根据Python随机出现的模式将大文件拆分为小文件

python - 努力解决Python中的 "a float is required error"

python - pip + 虚拟环境 : corrupted state

python - 为什么python嵌套函数不称为闭包?

python - 如何从日期时间中删除秒数?

当我们使用列表理解时,Python 会并行创建对象

python - 有没有什么方法可以检查Python(Django)中 View 函数的参数?

python - 基于频率的 pyplot.hexbin 中的十六进制大小

python - 如何在 python 中的匹配行之后获取行

python - 从 FASTA 文件中提取基因序列?