在 Python 中用字符串和整数生成字符串 [英] Making a string out of a string and an integer in Python

查看:38
本文介绍了在 Python 中用字符串和整数生成字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试取一个整数并在其前面加上b"并将其转换为字符串时出现此错误:

I get this error when trying to take an integer and prepend "b" to it, converting it into a string:

  File "program.py", line 19, in getname
    name = "b" + num
TypeError: Can't convert 'int' object to str implicitly

与此功能相关的:

num = random.randint(1,25)
name = "b" + num

推荐答案

name = 'b' + str(num)

name = 'b%s' % num

正如 S.Lott 所指出的,混合运算符 '%' 在 Python 3 及更高版本中已被弃用.我从 INTERCAL 中窃取了混合"这个名字,但这就是我谈论它的方式,之前至少想看到它印刷一次——就像渡渡鸟一样——它从地球表面消失了.

as S.Lott notes, the mingle operator '%' is deprecated for Python 3 and up. And I stole the name "mingle" from INTERCAL but that's how I talk about it and wanted to see it in print at least once before - like the dodo - it vanishes from the face of the earth.

这篇关于在 Python 中用字符串和整数生成字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆