2010-11-16 50 views
1

我想打印结果,例如:蟒纹和空白

for record in result: 
    print varone,vartwo,varthree 

我试图来连接它们是从SQL查询中的变量,但我得到的空白。我如何从“打印”中删除空格?我应该把结果输入一个变量,然后做一个'strip(newvar)'然后打印'newvar'?

+1

你在哪里得到的空白?请显示您获得的输出以及您期望的输出。 – 2010-11-16 12:06:19

+0

另外,你的代码不清楚。 varone等来自哪里以及它们是什么类型? – 2010-11-16 12:08:16

回答

4

此:

print "%s%s%s" % (varone,vartwo,varthree) 

将替换用值引号第一%svarone,第二%svartwo内容等

EDIT
作为Python 2.6你应该更喜欢这种方法:

print "{0}{1}{2}".format(varone,vartwo,varthree) 

(感谢Space_C0wb0y)

+0

您应该更喜欢使用['string.format'](http://docs.python.org/library/stdtypes.html#str.format)。 – 2010-11-16 12:09:30

+1

如果您希望将变量从“记录”中解压缩,您还可以编写“{0} {1} {2}”。格式(*记录)' – 2010-11-16 12:16:27

+1

您是第一个!所以你得到的勾号,非常感谢:D – Mathnode 2010-11-16 14:45:05

0

尝试

for record in result: 
    print ''.join([varone,vartwo,varthree]) 
+0

'AttributeError:'list'object has no attribute'join'' - try it另一种方式:'''.join([varone,vartwo,varthree])' – eumiro 2010-11-16 12:32:47

+0

谢谢eumiro,当我写下它时,它正在睡觉! :) – 2010-11-17 10:41:38

0

您将字符串传递到打印命令之前,只要使用字符串格式化:

for record in result: 
    print '%d%d%d' % (varone, vartwo, varthree) 

阅读关于Python字符串格式化here

+0

阅读* new * Python字符串格式[here](http://docs.python.org/library/stdtypes.html#str.format)。 – 2010-11-16 12:10:48

1

打印在变量之间放置空格并发出换行符。如果这只是打扰你的字符串之间的低语,那么只需在打印之前连接字符串即可。

print varone+vartwo+varthree 

真的,有很多方法可以做到这一点。它总是出现在打印之前创建一个结合您的值的新字符串。下面是我能想到的各种方法:

# string concatenation 
# the drawback is that your objects are not string 
# plus may have another meaning 
"one"+"two"+"three" 

#safer, but non pythonic and stupid for plain strings 
str("one")+str("two")+str("three") 

# same idea but safer and more elegant 
''.join(["one", "two", "three"]) 

# new string formatting method 
"{0}{1}{2}".format("one", "two", "three") 

# old string formating method 
"%s%s%s" % ("one", "two", "three") 

# old string formatting method, dictionnary based variant 
"%(a)s%(b)s%(c)s" % {'a': "one", 'b': "two", 'c':"three"} 

您也可以完全避免产生中间连接的字符串,用写的,而不是打印。

import sys 
for x in ["on", "two", "three"]: 
    sys.stdout.write(x) 

而且在Python 3.x中,你也可以自定义打印分隔符:

print("one", "two", "three", sep="") 
+0

与其他人一样,您应该使用[string.format](http://docs.python.org/library/stdtypes.html#str.format)。另外,没有人想知道varone等来自哪里?代码没有意义。 – 2010-11-16 12:11:45

+0

@ Space_C0wb0y:string.format很好,你应该使用它来写一个答案,而不是评论所有人。它必须是我的perl背景,但我仍然相信**有很多方法可以做到这一点**。纯粹的Python家伙似乎相信**只有一种真正的方式(它是用神圣的PEPs写成的)**,这可能是他们最讨厌的事情。还有varone等来自OP,他可能知道他们是什么。但是,好吧,我会从我的答案中删除无用的“记录”部分。 – kriss 2010-11-16 12:18:51

+0

@kriss:我没有回答的原因是OP还没有回答尚未解决的问题。这个问题的每个答案都是猜测,因为OP没有指定他的问题实际上是什么*。另外,我也相信有不止一种方法,但在这种情况下,坚持** The Way **有很好的推理,因为它使代码与未来版本的Python兼容。 – 2010-11-16 12:21:41