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

人盡茶涼 提交于 2019-12-04 07:14:38

问题


I am trying to print only the maximum occurring character and its count.

import collections

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

for lists, we have strip "".join method but how to deal with tuple the opposite way, i.e., removing the quotes and bracket.

So, here is what I want the output to be without quotes and brackets

input = "aaabucted"

output = ('a', 3)

I want the output to be a, 3.


回答1:


The quotes aren't in the data, they are just added when displaying the content on the screen. If you print the value rather than the string representation of the tuple you'll see there are no quotes or brackets in the data. So, the problem isn't "how do I remove the quotes and brackets?" but rather "how do I format the data the way I want?".

For example, using your code you can see the character and the count without the quotes and brackets like this:

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

And, of course, you can use string formatting:

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



回答2:


You can make a list and join it, first converting all to strings:

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


来源:https://stackoverflow.com/questions/33304115/how-to-remove-quotes-and-the-brackets-within-a-tuple-in-python-to-format-the-dat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!