为什么打印功能会打印圆括号? (例如:<< print(i,“这个数字是偶数”)>>输出:<<(1,'这个数字是偶数')>>

时间:2019-04-10 15:08:59

标签: python-3.x

我向您展示的代码非常简单,不是我正在使用的代码,但是它完美地解释了我在其他程序中遇到的问题。

我将发布代码以简化我的问题。 该代码的某些部分需要用意大利语发布,因为在打印特殊字符(字符-è)时我也遇到了问题,但注释后有翻译内容

我的代码

# ! /usr/bin/env python

#-*- coding: utf8 -*- 

for i in range(2): 
    if i % 2 == 0:
        print("I'm inside the if")
        print(i, "è un numero pari.\n") # i is even 
        continue
    print("Il blocco if è stato saltato, per cui...") # I'm outside of   the if
    print(i, "è un numero dispari\n") #i is odd

这是我在运行file.py时得到的结果:

Sono all interno del blocco if, per cui...

(0, '\xc3\xa8 un numero pari.\n')           [x1]

Il blocco if è stato saltato, per cui...    [y]

(1, '\xc3\xa8 un numero dispari')           [x2]

这是它应该打印的内容:(这也是我在运行python时将代码复制到bash中得到的内容)

Sono all interno del blocco if, per cui...

0 è un numero pari.

Il blocco if è stato saltato, per cui...

1 è un numero dispari

所以现在我有2个问题:

1。)为什么两个打印件(x1和x2)也打印出圆括号?

2。)为什么[x1]和[x2]打印“ \ xc3 \ xa8”而不是像[y]行那样的特殊字符“è”?

3 个答案:

答案 0 :(得分:0)

我在这里运行了代码(macos,python 3,“ python3 file.py”),输出正常:

I'm inside the if
0 è un numero pari.
Il blocco if è stato saltato, per cui...
1 è un numero dispari

您如何调用脚本?您的环境是什么?

此外,我强烈建议不要使用if ... else。

答案 1 :(得分:0)

您使用什么进行编码? 我在Win 10(64位)上尝试过-我得到以下输出:

for i in range(2):
if i % 2 == 0:
    print("I'm inside the if")
    print(i, "è un numero pari.\n") # i is even
    continue
print("Il blocco if è stato saltato, per cui...") # I'm outside of the if
print(i, "è un numero dispari\n") #i is odd

尝试在文件顶部设置编码:

import sys
reload(sys)
sys.setdefaultencoding('UTF8')

答案 2 :(得分:0)

您可能认为您正在使用Python 3,但实际上并非如此。您正在使用Python 2并获取其print 语句

$ python
Python 2.7.15 (default, Dec  2 2018, 12:54:06)
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(1,2)
(1, 2)
>>> from __future__ import print_function
>>> print(1,2)
1 2

第一个命令执行一条print语句,并打印 tuple (1,2)。启用print函数后,第二个命令使用两个参数1和2调用该函数。

作为打印元组的一部分,您要打印字符串的表示形式,而不是字符串本身,后者使用\x..显示非ASCII字符。