2010-11-16 90 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