【问题标题】:formatting print statement for different values and function call为不同的值和函数调用格式化打印语句
【发布时间】: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 返回一个元组,而不是具有numslettersother 属性的对象。
  • 有没有办法把它转换成我想要的样子??

标签: python function dictionary printing


【解决方案1】:

函数 match_string 返回一个元组,因此不能使用 x.nums 访问 而是尝试下面的代码

nums,letter,other = match_string(input("enter a sentence"))
print("There are:", + nums, + "numbers", + letters,+"letter", + other, +"other characters")

【讨论】:

  • 我从打印语句中删除了 + 并修复了它。谢谢
猜你喜欢
  • 1970-01-01
  • 2021-05-03
  • 2015-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多