Python字符串和整数连接
- 作者: 我是你的静静
- 来源: 51数据库
- 2023-01-15
问题描述
我想在 for 循环中使用附加的整数创建字符串.像这样:
I want to create string using integer appended to it, in a for loop. Like this:
for i in range(1,11): string="string"+i
但是它返回一个错误:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
连接字符串和整数的最佳方法是什么?
What's the best way to concatenate the String and Integer?
推荐答案
注意:
此答案中使用的方法(反引号)在更高版本的 Python 2 中已弃用,并在 Python 3 中删除.使用 str() 函数.
你可以使用:
string = 'string'
for i in range(11):
string +=`i`
print string
它将打印 string012345678910.
要获得 string0, string1 ..... string10 您可以按照@YOU 的建议使用它
To get string0, string1 ..... string10 you can use this as @YOU suggested
>>> string = "string" >>> [string+`i` for i in range(11)]
根据 Python3 更新
你可以使用:
string = 'string'
for i in range(11):
string +=str(i)
print string
它将打印 string012345678910.
要获得 string0, string1 ..... string10 您可以按照@YOU 的建议使用它
To get string0, string1 ..... string10 you can use this as @YOU suggested
>>> string = "string" >>> [string+str(i) for i in range(11)]
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
