【问题标题】:Have a sentence printed in Python without ' or ", using the print function使用 print 函数在 Python 中打印一个不带 ' 或 " 的句子
【发布时间】:2011-09-08 17:48:06
【问题描述】:

以下是我的代码,我正在使用 Python2.7

#list of angle couples
phipsi=[[48.6,53.4],[-124.9,156.7],[-66.2,-30.8],[-58.8,-43.1], \
[-73.9,-40.6],[-53.7,-37.5],[-80.6,-16.0],[-68.5,135.0], \
[-64.9,-23.5],[-66.9,-45.5],[-69.6,-41.0],[-62.7,-37.5], \
[-68.2,-38.3],[-61.2,-49.1],[-59.7,-41.1],[-63.2,-48.5], \
[-65.5,-38.5],[-64.1,-40.7],[-63.6,-40.8],[-66.4,-44.5], \
[-56.0,-52.5],[-55.4,-44.6],[-58.6,-44.0],[-77.5,-39.1], \
[-91.7,-11.9],[48.6,53.4]]
#minimal deviation tolerated for the 1st number
a=-57-30
#maximal deviation tolerated for the 1st number
b=-57+30
#minimal deviation tolerated for the 2nd number
c=-47-30
#maximal deviation tolerated for the 2nd number
d=-47+30
i=0
#Check if the couple fit into the intervals of numbers
while i < len(phipsi):
    if phipsi[i][0]>a and phipsi[i][0]<b:
        if phipsi[i][1]>c and phipsi[i][1]<d:
            print ('the couple ', phipsi[i] ,' has his angles in helix')
    else:
        print ('the couple ', phipsi[i] ,' does not have his angles in helix')
    i=i+1

这就是我得到的

('the couple ', [-55.4, -44.6], ' has his angles in helix')
('the couple ', [-58.6, -44.0], ' has his angles in helix')
('the couple ', [-77.5, -39.1], ' has his angles in helix')
('the couple ', [-91.7, -11.9], ' does not have his angles in helix')
('the couple ', [48.6, 53.4], ' does not have his angles in helix')

我怎样才能得到

the couple [-77.5, -39.1] has his angles in helix
the couple [-91.7, -11.9] does not have his angles in helix

我查看了帮助部分或其他符号,但无法弄清楚...谢谢您的帮助

【问题讨论】:

  • 去掉括号print 'the couple ', phipsi[i] ,' has his angles in helix'

标签: python printing python-2.7


【解决方案1】:

在 Python 2.x 中,print 不是函数,而是语句,并且它不包含打印对象列表周围的括号。在 Python 3.x 中,print 已更改为函数。您使用的是 Python 3.x 语法。

你有两个选择:

  1. 改用 Python 2.x 语法,跳过括号:print a, b, c
  2. 添加from __future__ import print_function 以禁用打印语句并改用打印功能。这允许在最近的 Python 2.x 中使用 Python 3.x 语法。

目前,您正在打印单个 tuple,并且您看到的是该元组的 repr,即使用 Python 3.x 打印功能使用 print((a,b,c)) 会得到什么。

注意:print 会自动添加空格,无需将它们添加到您的字符串中。

【讨论】:

  • 那个 print 是 Python 2.x 中的一个语句,这只是极少数错误之一。
【解决方案2】:

使用字符串格式.. 来吧:

while i < len(phipsi):
    if phipsi[i][0]>a and phipsi[i][0]<b:
        if phipsi[i][1]>c and phipsi[i][1]<d:
            print ('the couple [%+.2f, %+.2f] has his angles in helix' % (phipsi[i][0], phipsi[i][1]))
    else:
        print ('the couple [%+.2f, %+.2f] does not have his angles in helix' % (phipsi[i][0], phipsi[i][1]))
    i=i+1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多