如何使用python打印字符串作为这样的处理

时间:2015-10-04 11:45:36

标签: python string printing

我想编写一个函数来打印出这样的字符串:

Found xxxx...
x的

是由另一个函数计算的结果。它只打印一行,顺序但不是一次。示例:我想打印my_name,但它只是m ....而我的....和我的_....,只是在行。 我可以用python做到这一点吗? 对不起我无法用英语清楚解释。

更新

示例代码;

import requests

url = 'http://example.com/?get='
list = ['black', 'white', 'pink']

def get_num(id):
    num = requests.get(url+id).text
    return num
def print_out():
    for i in list:
        num = get_num(i)
if __name__ == '__main__':
    #Now at main I want to print out 2...  (for example, first get_num value is 2) and after calculating 2nd loop print_out, such as 5, it will update 25...
    #But not like this:
    #2...
    #25...
    #25x...
    #I want to it update on one line :)

2 个答案:

答案 0 :(得分:2)

如果您希望在同一行中打印输出,并且您使用的是Python 2.7,则可以执行以下操作。

第一种方法Py2.7 只需这样做:

# Note the comma at the end
print('stuff'),

将打印件保持在同一行,但

之间会有空格

第二种方法Py2.7

import sys
sys.stdout.write("stuff")

这将在没有空格的同一行上打印所有内容。但是要小心,因为它只需要str类型。如果你传递int,你将获得例外。

因此,在一个代码示例中,为了说明两者的用法,您可以执行以下操作:

import sys
def foo():
    data = ["stuff"]
    print("Found: "),
    for i in data:
        sys.stdout.write(i)
    #if you want a new line...just print
    print("")

foo()

输出: Found: stuff

Python 3信息

只是要添加有关在Python 3中使用它的额外信息,您可以简单地执行此操作:

print("stuff", end="")

从文档here

中获取的输出示例
>>> for i in range(4):
...     print(i, end=" ")
... 
0 1 2 3 >>> 
>>> for i in range(4):
...     print(i, end=" :-) ")
... 
0 :-) 1 :-) 2 :-) 3 :-) >>> 

答案 1 :(得分:0)

s = "my_name"
for letter in range(len(s)):
    print("Found",s[0:letter+1])

而不是'您可以使用所需的返回值调用函数。