繁体   English   中英

如何在Python的同一行上打印来自不同函数的两个语句

[英]How to print two statements from different functions on the same line in Python

我试图在Python 2.7(或3.4)的同一行上打印两个输出语句。 打印语句不会一个接一个地出现,例如print a / print b。 我的程序使用329(例如),然后以字为单位返回该值-三百二十九。 因此,它将确定300个零件并打印,然后确定29个零件并打印。

if (main == hundreds[index]):
    print hundreds_words[index]
for location in range (0, 10):
    if (difference == twenties[location]):
        print twenties_words[location]

我想将29与300印刷在同一行上。 我想我可以尝试建立一个解决方案,但我想知道Python是否具有执行此操作的过程。

是的,它确实。 您只需要告诉print不要在第一行之后添加新行。 在python2中,您可以通过添加结尾逗号来实现此目的: print mystring, 在python3中, print是具有end关键字参数的函数: print(mystring, end="")

简单的方法是重写您的数字转单词功能,并使其返回一个字符串而不是打印它。

更复杂的方法是重定向stdout以将print输出捕获为字符串。

编辑:看起来我使它变得比必要的更为复杂; 你可以尝试

output_words = []
if (main == hundreds[index]):
    output_words.append(hundreds_words[index])
for location in range (0, 10):
    if (difference == twenties[location]):
        output_words.append(twenties_words[location])
return " ".join(output_words)

在python 2中,您可以使用结束print语句,以指示不以换行符终止,例如:

print hundreds_words[index], 

在python 3(或py2 from __future__ import print_function )中,您需要显式定义end ,例如:

print(hundreds_words[index], end=' ')

但是理想情况下,您只需要将所有结果收集到一个list ,然后在最后join()即可。

result = []
if (main == hundreds[index]):
    result.append(hundreds_words[index])
for location in range (0, 10):
    if (difference == twenties[location]):
        result.append(twenties_words[location])

print(' '.join(result))

始终设计函数以返回值,而不是打印它们(这是更多的Pythonic!)。 因此,您应该以这种方式修改代码:

# FOR PYTHON 2.x

if (main == hundreds[index]):
    print hundreds_words[index], # Note the comma
for location in range (0, 10):
    if (difference == twenties[location]):
        print twenties_words[location]

# FOR PYTHON 3.x

if (main == hundreds[index]):
    print(hundreds_words[index], end=" ") # end=" " will override the default '\n' and leave a space after the string
for location in range (0, 10):
    if (difference == twenties[location]):
        print(twenties_words[location])

还有第三个选项,更具可伸缩性: 所有数据包装在列表中,然后打印所有内容。

printable = []

if (main == hundreds[index]):
    printable += hundreds_words[index]
for location in range (0, 10):
    if (difference == twenties[location]):
        printable += twenties_words[location]

print(" ".join(printable))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM