【发布时间】:2020-10-23 06:48:22
【问题描述】:
我正在练习我的 python 并尝试为 match_string 格式化以下代码的打印语句,以便以这种格式打印:
There are 5 numbers, 4 letters and 2 other characters.
我已经尝试过:
print("There are:", + x.nums, + "numbers", +x.letters,+"letter", + x.other, +"other characters")
我得到了错误:
AttributeError: 'tuple' object has no attribute 'nums'
我也认为我的 getDupes 部分也有问题,但我不知道是什么,它只是打印出来的一样。
这是我的代码:
def match_string(words):
nums = 0
letter = 0
other = 0
for i in words :
if i.isalpha():
letter+=1
elif i.isdigit():
nums+=1
else:
other+=1
return nums,letter,other
def getDupes(x):
d = {}
for i in x:
if i in d:
if d[i]:
yield i
d[i] = False
else:
d[i] = True
x = match_string(input("enter a sentence"))
c = getDupes(x)
print(x)
#print("There are:", + str(x.nums), + "numbers", +x.letters,+"letter", + x.other, +"other characters")
print("PRINT",x)
【问题讨论】:
-
return nums,letter,other返回一个元组,而不是具有nums、letters或other属性的对象。 -
有没有办法把它转换成我想要的样子??
标签: python function dictionary printing