python - TypeError:只能将str(不是“int”)连接到str123
问题描述
运行以下代码后出现错误。
这是代码:
a=input("enter the string value")
b=int(input("enter the number"))
c=a+b
print(c)
这是结果:
enter the string value xyz
enter the number 12
Traceback (most recent call last):
File "e:/python learning/error1.py", line 3, in <module>
c=a+b
TypeError: can only concatenate str (not "int") to str
解决方案
在 Python 中,不能将字符串添加到 int。为此,您可以使用不同的方法,例如format
:
a = input("enter the string value")
b = int(input("enter the number"))
c = "{}{}".format(a, b)
该format
函数将对象作为参数,并通过str
对象的表示来表示它们。
在 Python 3.6 及更高版本中,您可以使用f-string
that 将执行相同的操作,方法是在字符串之前format
添加一个并在内部添加参数,例如:f
c = f'{a}{b}'
a
这两个选项都将存储和b
的串联c
。
print
使用该功能还有另一个选项,例如:
print(a, b, sep="")
该print
函数采用由 a 分隔的所有参数,
并打印str
对象的表示 - 就像这样format
做一样。默认情况下sep
,打印选项是" "
在参数之间打印的空格。通过将其更改为""
它将按顺序打印参数,中间没有空格。
可以使用此选项,而无需将 和 的串联存储a
在b
另一个变量中作为c
.
推荐阅读
- c# - 为端口转发运行 Open.NAT 库时出现问题
- javascript - 如何解决“找不到构建工具修订版 26.0.3”
- caching - Redis 中的“节点”到底是什么
- c# - 如何为我的任务执行添加顺序?
- bash - 用于获取 hdfs 中所有零件文件的行数的 shell 脚本
- c# - 如何将 Hub 内容从任何服务器带到*另一台服务器*项目 Hub?
- python - matplotlib 中的 figsize 不会改变图形大小?
- r - 如何使用字符串连接定义聚集函数的关键参数
- android - Android 应用程序:如何向 Surface 显示连续的 RGBA 字节 [] 帧?
- html - 如何使导航栏中的引导按钮跨越整个导航栏