如何删除 python 中元组中的引号和括号以格式化数据

How to remove quotes and the brackets within a tuple in python to format the data

我试图只打印出现次数最多的字符及其计数。

import collections

s = raw_input()
k = (collections.Counter(s).most_common(1)[0])

对于列表,我们有 strip "".join 方法,但是如何以相反的方式处理元组,即删除引号和括号。

所以,这是我希望输出不带引号和括号的内容

input = "aaabucted"

output = ('a', 3)

我希望输出为 a, 3

引号不在数据中,只是在屏幕上显示内容时添加的。如果您打印值而不是元组的字符串表示,您将看到数据中没有引号或括号。所以,问题不是 "how do I remove the quotes and brackets?",而是 "how do I format the data the way I want?"。

例如,使用您的代码,您可以看到没有引号和括号的字符和计数,如下所示:

print k[0], k[1]  # python 2
print(k[0], k[1]) # python 3

当然,您可以使用字符串格式:

print "%s, %i" % k   # python 2
print("%s, %i" % k)  # python 3

您可以创建一个列表并加入它,首先将所有内容转换为字符串:

",".join([str(s) for s in list(k)])