在 Python 中用一个字符串和一个整数创建一个字符串 [英] Making a string out of a string and an integer in Python

查看:39
本文介绍了在 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天全站免登陆