问题1:
word = 'fast'
print '"',word,'" is nice'给出输出为" fast " is nice.
我如何获得输出,"fast" is nice即我希望前后删除空格word?
问题2:
def faultyPrint():
print 'nice'
Run Code Online (Sandbox Code Playgroud)
print 'Word is', faultyPrint() 给我输出为
Word is nice
None
Run Code Online (Sandbox Code Playgroud)
我希望输出Word is nice和None删除.
我不想要输出
print 'Word is'
faultyPrint()
Run Code Online (Sandbox Code Playgroud)
因为它给了我输出
Word is
nice
Run Code Online (Sandbox Code Playgroud)
如何在不更改功能和保持相同输出格式的情况下执行此操作?
更具扩展性的方法如下.
word = "fast"
print('"{0}" is nice'.format(word))
Run Code Online (Sandbox Code Playgroud)
(对于括号:如果只传递一个参数,它们没有区别,并且在大多数情况下免费提供python3兼容性)
有关此文档的更多详细信息,请参阅Python字符串格式语法(此处的示例).
在不修补函数的情况下修复此问题的唯一方法是不在打印结束时创建换行符:
print "Word is",
faultyPrint()
Run Code Online (Sandbox Code Playgroud)
如果你想保持Python3向上兼容,你必须这样做:
from __future__ import print_function #put that at the head of your file
print("Word is ", end="")
faultyPrint()
Run Code Online (Sandbox Code Playgroud)
(注意(非显而易见的)差异:在Python3中,你需要在字符串的末尾加一个空格)
通常,尽管返回要打印的值更合适,但最好是最合适的数据类型(即不是",".join(foo)列表,返回列表并在最外层函数中进行连接).这提供了逻辑和表示的可重用性和分离.