Python输出tuple元组时如何去掉打印结果两侧的括号
问题原因
你直接在f-string中传入元组对象时,默认调用的是元组的__str__()方法输出,所以会自带两侧括号、元素之间的逗号和空格格式。
解决方法
方法1:按索引取元组元素拼接(适合已知元组长度的场景)
直接通过下标访问元组的每个元素,自定义拼接格式:
exam_st_date = (11, 12, 2014) print(f'The examination will start from {exam_st_date[0]}/{exam_st_date[1]}/{exam_st_date[2]}')
运行输出:
The examination will start from 11/12/2014
方法2:字符串join拼接(适配任意长度的元组,可自定义分隔符)
先把元组的所有元素转为字符串类型,再用你需要的分隔符拼接:
exam_st_date = (11, 12, 2014) # 这里用斜杠作为分隔符,也可以换成逗号、空格等其他符号 date_str = '/'.join(map(str, exam_st_date)) print(f'The examination will start from {date_str}')
运行输出和上面一致。如果需要用逗号加空格分隔元素,只要把分隔符改为, 即可。
方法3:解包元组配合print的sep参数
用*解包元组的所有元素,通过print的sep参数设置元素之间的分隔符:
exam_st_date = (11, 12, 2014) print('The examination will start from', *exam_st_date, sep=' ')
运行输出:
The examination will start from 11 12 2014
内容的提问来源于stack exchange,提问作者Phong Diep
相关产品推荐
相关产品推荐

