开发者

python print and whitespace

开发者 https://www.devze.com 2023-01-25 13:57 出处:网络
I am trying to print a result for example: for record in result: print varone,vartwo,varthree 开发者_如何学JAVA

I am trying to print a result for example:

for record in result:
    print varone,vartwo,varthree
开发者_如何学JAVA

I am trying to concatenate the variables which are from an SQL query, but I am getting whitespace. How can I strip whitespace from a 'print'? Should I feed the result into a variable then do a 'strip(newvar)' then print the 'newvar'?


This:

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

will replace the first %s in the quotes with the value in varone, the second %s with the contents of vartwo, etc.

EDIT:
As of Python 2.6 you should prefer this method:

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

(Thanks Space_C0wb0y)


print put whitespace between variables and emit a newline. If this is just the whistespaces between strings that bother you, just concatenate the strings before printing.

print varone+vartwo+varthree

Really, there is (much) more than one way to do it. It always comes out creating a new string combining your values before printing it. Below are the various ways I can think of:

# 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"}

You can also avoid creating intermediate concatenated strings completely and use write instead of print.

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

And in python 3.x you could also customize the print separator:

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


Just use string formatting before you pass the string to the print command:

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

Read about Python string formatting here


Try

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

精彩评论

暂无评论...
验证码 换一张
取 消