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

查看:186
本文介绍了在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 中偷走了mingle这个名字,但这就是我谈论它的方式。我想在之前至少看过一次 - 比如渡渡鸟 - 它从地球上消失了。

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天全站免登陆