为什么此format()函数不起作用?

时间:2020-07-07 19:40:22

标签: python python-3.x

我写的是这段代码,就像写在书上一样:

if __name__=='__main__':
    print ('The ASCII character of 0 is 1' .format('A',65))

正如书中所说,输出应为The ASCII character of A is 65,但显示为The ASCII character of 0 is 1

为什么不起作用?请帮忙。

2 个答案:

答案 0 :(得分:1)

您需要为占位符设置format方法将在其中插入数据的位置:

赞:

if __name__=='__main__':
    print ('The ASCII character of {} is {}'.format('A',65))

或使用关键字

if __name__=='__main__':
    print ('The ASCII character of {char} is {num}'.format(char='A', num=65))

或使用索引

if __name__=='__main__':
    print ('The ASCII character of {0} is {1}'.format('A', 65))

答案 1 :(得分:0)

if __name__=='__main__':
    print ('The ASCII character of {0} is {1}' .format('A',65))

占位符必须用{0}之类的大括号来写。