如何解决在python3 format函数中打印撇号的符号
请帮助我解决输出句子中包含撇号'符号和标准format()函数的问题。我以Mark Lutz 2013的第31章“学习Python,第五版”为例,它具有函数,实例,方法和带有打印重载的实例—请参见下面的代码及其内容。解释器信息-Linux上的Python 3.7.3(默认,2020年7月25日,13:03:44)[GCC 8.3.0]。 示例代码以及带有format()和print()函数的输出:
def square(arg): # Simple functions def or lambda
return arg ** 2
class Sum: # Calliable instance
def __init__(self,val):
self.val = val
def __call__(self,arg):
return self.val + arg
class Product: # Bound method
def __init__(self,val):
self.val = val
def method(self,arg):
return self.val * arg
class Negate:
def __init__(self,val): # Operator print overloading
self.val = -val
def __repr__(self):
return str(self.val)
if __name__ == '__main__':
Sobject = Sum(2)
pobject = Product(3)
actions = [square,Sobject,pobject.method,Negate] # function,instance,method,instance with print() overloading
table = {act(5): act for act in actions} # Dictionary comprhension
for (key,value) in table.items(): # Printing with format
print('{0:2} => {1}'.format(key,value))
output print correct first three rows and raise exceptions when trying print fourth row which contains mean (-5,<class '__main__.Negate'>) with apostrophe ' symbol
25 => <function square at 0x7fdba0d64840>
7 => <__main__.Sum object at 0x7fdba00a8d30>
15 => <bound method Product.method of <__main__.Product object at 0x7fdba00a8d68>>
Traceback (most recent call last): TypeError: unsupported format string passed to Negate.__format__
print(table) # using standard print() function
output is correct without any errors,see bellow:
dict_items(
[(25,<function square at 0x7fdba0088d90>),(7,<__main__.Sum object at 0x7fdba00215c0>),(15,<bound method Product.method of <__main__.Product object at 0x7fdba0021390>>),(-5,<class '__main__.Negate'>)])
我知道标准print()函数内部的打印撇号'-添加转义字符'可以在单引号内的字符串中添加撇号,或者将单引号替换为双引号:
print('I\'m studying Python') → I'm studing Python
or
print("I'm studying Python") -> I'm studying Python
解决方法
到Pranav Hosangadi
示例取自第31章:“使用类进行设计”第952-953页-类Negate仅具有def init (self,val)的构造函数以及def repr 重载print()的构造函数>(self):并且 format 和此示例中描述的对象的其他嵌入方法没有任何其他重载。本书中的示例在第953页上有正确的输出-5 =>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。