python - TypeError:无法在 python 2.7 中连接“str”和“tuple”对象
问题描述
我parameterized functions
在python中使用。我正在传递一些字符串值并访问它的值。
这就是我的函数定义的样子:
import constants
def print_error_table(self, header1, errormsg, icon):
# for header1
print(constants.GREEN)
print(constants.REPORT_HEADER_ERR)
print(constants.DATE_TIME)
print(constants.SPACE)
start = "| | "+constants.ICON_BOX
header1_count = len(header1)
available_space_for_first_part = 37 - (len(start) + header1_count)
s = ""
print(constants.REPORT_ROOF)
print(constants.REPORT_COLUMNS)
print(constants.REPORT_FLOOR)
print(constants.REPORT_MIDDLE)
print(start),
print(" "+constants.NC+header1+constants.GREEN),
for i in range(available_space_for_first_part):
s += " "
print(s),
print("|"),
# right part
end = " "
end2 = "| |"
s2 = ""
icon_count = len(icon)
available_space_for_second_part = 31 - (len(end) + icon_count)
print(end),
print(icon),
for i in range(available_space_for_second_part):
s2 += " "
print(s2),
print(end2)
print(constants.REPORT_SHORT_HORIZONTAL_LINE)
print(constants.REPORT_MIDDLE_NO_MIDDLE_SEPTUM)
# print(len(constants.SPACE)) # 84
# print first 40 characters
start = "| |"
print(start),
s3 = ""
for i in range(12):
print(" "),
print(constants.RED),
msg = "1.) " + errormsg,
print(""+msg), # this is where my error is getting
print(constants.GREEN),
# print(constants.RED+constants.ICON_CROSS+msg+constants.GREEN),
for i in range(12, 57 - len(msg)-1):
s3 += " "
print(s3),
print("| |"),
print("")
print(constants.REPORT_MIDDLE_NO_MIDDLE_SEPTUM)
print(constants.REPORT_MIDDLE)
print(constants.REPORT_FLOOR)
print(constants.REPORT_FOOTER)
这是我从中调用此函数的另一个 python 文件。
error_message = "\"etcd\" is impaired\n"
print_error_table(self, "ETCD", error_message, constants.ICON_CROSS)
我得到这个错误:
文件“/home/jananath/Desktop/python-script/2/bitesizetrouble/report_error.py”,第 57 行,在 print_error_table print(""+msg),TypeError:无法连接 'str' 和 'tuple' 对象
问题是我传递的值(即error_message
)没有传递,因为string
它是某种由于某种原因而改变的文本。
我之所以这么说是因为,在上面的(第一个)命令中,它说的是print(""+str(msg))
,而不是这个,当我尝试print(msg),
它时,它会给出一些像这样的奇怪输出。
(`"etcd" 受损\n',)
你可以看到两边parenthesis
各有两个。它来自哪里以及为什么我不能将传递给函数的字符串与另一个字符串连接起来(即print(""+str(msg))
更新:我正在使用 , 来停止 print() 打印新行。这是我在 python 2.7.5 中应该这样做的方式
解决方案
您的代码中充满了逗号,而您又将逗号放在了错误的位置。
您可以通过在字符串赋值的末尾添加一个逗号来创建一个包含一个元素的元组。看:
>>> foo = "bar"
>>> print(foo)
bar
>>> foo = "bar",
>>> print(foo)
('bar',)
我建议您从 python.org ( https://docs.python.org/3/tutorial/index.html ) 上的 Python 教程开始。严重地。并且不要学习 Python 2,它不再是。严重地。
推荐阅读
- laravel - Laravel 表单提交返回错误 302,我的路由有问题吗?
- python - Python中的嵌套字典 - 错误缠身
- django - 使用 Elastic Beanstalk 部署 Vue JS Django 应用程序
- c++ - 此范围内未声明错误“xy”
- aws-fargate - EKS 的 Fargate 上的 Pod 无权访问 AWS 默认凭证
- javascript - 如何在ionic 4中移动搜索栏右侧的搜索栏搜索图标
- jquery - 使用 jQuery 向服务器发送数据时的 net::ERR_CONNECTION_TIMED_OUT
- mongodb - 如何在 mongodb 中更新日期字段格式
- c++ - 在链表中手动插入第五个元素
- python - 如何将 json 数据导出为 csv 或 txt 文件