【问题标题】:Why Python is outputting parenthesis and quotes in my print command?为什么 Python 在我的打印命令中输出括号和引号?
【发布时间】:2018-05-31 15:22:29
【问题描述】:

我注意到我的 python 脚本正在打印括号和引号,例如以下行:

print ("Password set saved on file:", ps_file_name)

输出以下内容:

('Password set saved on file:', '20180531-1719__password_set.txt')

而预期的结果是:

Password set saved on file: 20180531-1719__password_set.txt

我做错了什么?

编辑:我的错误是我将脚本运行为:

Python pmake.py

而不是脚本直接运行3.6版本

【问题讨论】:

  • 这是python 2.7,对吧?那么不应该有括号;否则你打印一个tuple 包含你的对象的repr
  • 你必须使用 Python 2,所以括号是不必要的。你可以print "Password set", ps_file_name
  • @hiroprotagonist python 3.6
  • @S.Redrum 如果是 Python 3,你就不会遇到这个问题。它必须是 Python 2。
  • @khelwood 我注意到我同时拥有2.73.6 版本如何使3.6 版本在Windows 中作为默认版本有效?

标签: python


【解决方案1】:

这是因为 print 在给定多个参数时会写入一个元组

str1 = "Hello"
str2 = "world"
print (str1, str2) #will print : (hello, world)

你想要的是

str1 = "Hello"
str2 = "world"
str3 = str1 + str2
print (str3) #will print : Hello world

或者说

print (str1 + str2)  #see how you give only one argument by concatenating str1 and str2 ?



请注意,如果要将两个本身不是字符串的对象相加,则必须将它们转换为字符串(就像有字符串一样)。即使两个对象都可以单独正确打印。
这是因为python不能把两个不兼容的东西加起来。

x = "your picture is"
y = someimage.jpg
print(x,y) # works well and dandy, gives a tuple
print(x + y)#fails, python can t add up a string and an image
print(x + str(y))# works because str(y) is y casted into a string

请注意,并非所有内容都可以转换为字符串

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 2015-03-22
    • 2023-03-26
    • 2017-02-25
    • 1970-01-01
    相关资源
    最近更新 更多