简体   繁体   English

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

[英]How to use python to print strings as processing like this

I want to write a function to print out string like this: 我想编写一个函数来打印出这样的字符串:

Found xxxx...

for x is result calculating by another function. 因为x是另一个函数计算的结果。 It only print one line, sequential, but not one time. 它仅连续打印一行,而不打印一次。 Example: I want to print my_name but it'll be m.... and my.... and my_...., at only line. 示例:我想打印my_name,但是它将仅在一行上显示m ....和my ....和my_....。 Can i do this with python? 我可以用python吗? Sorry I can't explain clearly by english. 对不起,我用英语说不清楚。

UPDATE UPDATE

Example code; 示例代码;

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 :)

If you are looking to print your output all in the same line, and you are using Python 2.7, you can do a couple of things. 如果您希望在同一行中全部打印输出,并且您正在使用Python 2.7,则可以做几件事。

First Method Py2.7 Simply doing this: 第一种方法Py2.7只需执行以下操作:

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

Will keep the print on the same line but there will be a space in between 将打印保持在同一行上,但两者之间会有一个空格

Second Method Py2.7 第二种方法Py2.7

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

This will print everything on the same line without a space. 这将在同一行上打印所有内容而没有空格。 Be careful, however, as it only takes type str . 但是要小心,因为它只需要输入str If you pass an int you will get an exception. 如果您传递一个int您将获得一个例外。

So, in a code example, to illustrate the usage of both you can do something like this: 因此,在一个代码示例中,为了说明这两种用法,您可以执行以下操作:

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()

Output: Found: stuff 输出: Found: stuff

Python 3 Info Python 3信息

Just to add extra info about using this in Python 3, you can simply do this instead: 只需添加有关在Python 3中使用此功能的额外信息,您可以简单地执行以下操作:

print("stuff", end="")

Output example taken from docs 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 :-) >>> 
s = "my_name"
for letter in range(len(s)):
    print("Found",s[0:letter+1])

Instead of 's' you can just call function with your desired return value. 除了使用“ s”,您还可以使用所需的返回值调用函数。

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

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